1. 程式人生 > 其它 >Golang語言中的方法定義用法分析

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())
}