1. 程式人生 > >Go語言的方法值和方法表達式

Go語言的方法值和方法表達式

pac ESS 地址 pointer 方法 package fun 變量 import

// code_20_struct_method_expression project main.go package main import ( "fmt" ) //方法表達式:也即“方法對象賦值給變量” //兩種使用方式: //1)隱式調用, struct實例獲取方法對象---->方法值 //2)顯示調用, struct類型獲取方法對象, 須要傳遞struct實例對象作為參數。---->方法表達式 type Person struct { name string sex byte age int } func (p *Person) PrintInfoPointer() { fmt.Printf("%p, %v\n", p, p) } func (p Person) PrintInfoValue() { fmt.Printf("%p, %v\n", &p, p) } func main() { //直接調用 p := Person{"ck_god", ‘m‘, 18} p.PrintInfoPointer() fmt.Println("---------------\n") //方法表達式 pFunc1 := (*Person).PrintInfoPointer pFunc1(&p) pFunc2 := Person.PrintInfoValue pFunc2(p) fmt.Println("---------------\n") //方法值 pFunc3 := p.PrintInfoPointer pFunc3() pFunc4 := p.PrintInfoValue pFunc4() fmt.Println("---------------\n") //備註:pFunc2和pFunc4的內存地址是不一樣的;pFunc1和pFunc3的內存地址是一致的 }

結果如下:

0xc000050400, &{ck_god 109 18}
---------------

0xc000050400, &{ck_god 109 18}
0xc000050480, {ck_god 109 18}
---------------

0xc000050400, &{ck_god 109 18}
0xc0000504e0, {ck_god 109 18}
---------------

Go語言的方法值和方法表達式