[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) SetInfoValuePointer ()  {
    fmt.Printf("SetInfoValuePointer: %p, %v\n", p, p)
}

func main() {
    p := Person{"mike", 'm', 18}
    fmt.Printf("main: %p, %v\n", &p, p)
    p.SetInfoValuePointer()//传统调用方式
    pFunc := p.SetInfoValuePointer //这个就是方法值,调用函数时,无需再传递接收者,隐藏了接收者
    pFunc() //等价于p.SetInfoPointer()
    
    vFunc := p.SetInfoValue  //这里完成内容拷贝的操作
    vFunc()
}

执行的结果为

main: 0xc000044400, {mike 109 18}
SetInfoValuePointer: 0xc000044400, &{mike 109 18}
SetInfoValuePointer: 0xc000044400, &{mike 109 18}
SetInfoValue: 0xc0000444a0, {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) SetInfoValuePointer ()  {
    fmt.Printf("SetInfoValuePointer: %p, %v\n", p, p)
}

func main() {
    p := Person{"mike", 'm', 18}
//方法值,f := p.setinfovaluepointer隐藏了接收者
//方法表达式
f := (*Person).SetInfoValuePointer f(&p) //显示的把接收者传递过去 f2 := (Person).SetInfoValue f2(p) //显示的把接收者传递过去
}

执行结果

SetInfoValuePointer: 0xc000044400, &{mike 109 18}
SetInfoValue: 0xc000044460, {mike 109 18}

本人表达方式不好就不总结 了,看了下面的区别相信每个人都有自己的理解

p := Person("mike", 'm', 18)
pFunc := p.SetInfoValuePointer        方法值 
pFunc ()
------------------------------------------
f2 := (*Person).SetInfoValuePointer
p := Person{"mike", 'm', 18}         方法表达式
f2(&p)