go 结构的方法2

你能够对包中的 任意 类型定义任意方法,而不单单是针对结构体。import

可是,不能对来自其余包的类型或基础类型定义方法。基础

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())
}
相关文章
相关标签/搜索