go語言之進階篇方法值與方法表達式

方法值


package main
 
import "fmt"
 
type Person struct {
    name string //名字
    sex  byte   //性別, 字符類型
    age  int    //年齡
}
 
func (p Person) SetInfoValue() {
    fmt.Printf("SetInfoValue: %p, %v\n", &p, p)
}
 
func (p *Person) SetInfoPointer() {
    fmt.Printf("SetInfoPointer: %p, %v\n", p, p)
}
 
func main() {
    p := Person{"mike", 'm', 18}
    fmt.Printf("main: %p, %v\n", &p, p)
 
    p.SetInfoPointer() //傳統調用方式
 
    //保存方式入口地址
    pFunc := p.SetInfoPointer //這個就是方法值,調用函數時,無需再傳遞接收者,隱藏了接收者
    pFunc()                   //等價於 p.SetInfoPointer()
 
    vFunc := p.SetInfoValue
    vFunc() //等價於 p.SetInfoValue()
 
}

執行結果:

main: 0xc00005a400, {mike 109 18}
SetInfoPointer: 0xc00005a400, &{mike 109 18}
SetInfoPointer: 0xc00005a400, &{mike 109 18}
SetInfoValue: 0xc00005a4a0, {mike 109 18}

方法表達式

package main
 
import "fmt"
 
type Person struct {
    name string //名字
    sex  byte   //性別, 字符類型
    age  int    //年齡
}
 
func (p Person) SetInfoValue() {
    fmt.Printf("SetInfoValue: %p, %v\n", &p, p)
}
 
func (p *Person) SetInfoPointer() {
    fmt.Printf("SetInfoPointer: %p, %v\n", p, p)
}
 
func main() {
    p := Person{"mike", 'm', 18}
    fmt.Printf("main: %p, %v\n", &p, p)
 
    //方法值   f := p.SetInfoPointer //隱藏了接收者
    //方法表達式
    f := (*Person).SetInfoPointer
    f(&p) //顯式把接收者傳遞過去 ====》 p.SetInfoPointer()
 
    f2 := (Person).SetInfoValue
    f2(p) //顯式把接收者傳遞過去 ====》 p.SetInfoValue()
}

執行結果:

main: 0xc00005a400, {mike 109 18}
SetInfoPointer: 0xc00005a400, &{mike 109 18}
SetInfoValue: 0xc00005a480, {mike 109 18}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章