Skip to content

Latest commit

 

History

History
26 lines (23 loc) · 978 Bytes

10.方法 method.md

File metadata and controls

26 lines (23 loc) · 978 Bytes

方法 method

-Go 中虽没有 class ,但依旧有 method
-通过显示说明 receiver 来实现与某个类型的组合
-只能为同一个包中的类型定义方法
-receiver 可以时类型的值或者指针 -不存在方法重载
-可以使用值或指针来调用方法,编译器会字段完成转换
-从某种意义上来说,方法是函数的语法糖,因为 receiver 其实就是方法所接受的第一个参数 ( Method Value vs.Method Expression )
-如果外部结构和嵌入结构存在同名方法,则优先调用外部结构的方法
-类型别名不会拥有底层类型所附带的方法
-方法可以调用结构中的非公开字段

//课后习题
type TZ int

func main() {
    //零值 0
    var a TZ
    a.Increase(100)
    fmt.Println(a)
}

func (tz *TZ) Increase(num int) {
    //对 int 强制类型转换为 TZ
    *tz += TZ(num)
}