Golang语言中的方法定义用法分析

时间:2022-05-04
本文章向大家介绍Golang语言中的方法定义用法分析,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

事实上,可以对包中的任意类型定义任意方法,而不仅仅是结构体。 不能对来自其他包的类型或基础类型定义方法。

package main
import (
    "fmt"
    "math"
)
type MyFloat float64
func (f MyFloat) Abs() float64 {
    if f < 0 {
        return float64(-f)
    }
    return float64(f)
}
func main() {
    f := MyFloat(-math.Sqrt2)
    fmt.Println(f.Abs())
}