下面由golang教程栏目给大家介绍golang中方法的receiver为指针和不为指针的区别,希望对需要的朋友有所帮助!

golang中方法的receiver为指针和不为指针的区别

前言

最近看网站有同学提问golang中方法的receiver为指针和不为指针有什么区别,在这里我以简单易懂的方法进行说明,帮助刚刚学习golang的同学.

方法是什么

其实只要明白这个原理,基本就能理解上面提到的问题.

方法其实就是一种特殊的函数,receiver就是隐式传入的第一实参.

举个例子

type test struct{
    name string
}

func (t test) TestValue() {
}

func (t *test) TestPointer() {
}

func main(){
    t := test{}
    
    m := test.TestValue
    m(t)
    
    m1 := (*test).TestPointer
    m1(&t)    
}

是不是很简单就明白了呢?现在我们来加入代码,来看看指针和非指针有什么区别.

type test struct{
    name string
}

func (t test) TestValue() {
    fmt.Printf("%p\n", &t)
}

func (t *test) TestPointer() {
    fmt.Printf("%p\n", t)
}

func main(){
    t := test{}
    //0xc42000e2c0
    fmt.Printf("%p\n", &t)
    
    //0xc42000e2e0
    m := test.TestValue
    m(t)
    
    //0xc42000e2c0
    m1 := (*test).TestPointer
    m1(&t)    

}

估计有的同学已经明白了,当不是指针时传入实参后值发生了复制.所以每调用一次TestValue()值就发生一次复制.
那如果涉及到修改值的操作,结果会是怎样呢?

type test struct{
    name string
}

func (t test) TestValue() {
    fmt.Printf("%s\n",t.name)
}

func (t *test) TestPointer() {
    fmt.Printf("%s\n",t.name)
}

func main(){
    t := test{"wang"}

    //这里发生了复制,不受后面修改的影响
    m := t.TestValue
    
    t.name = "Li"
    m1 := (*test).TestPointer
    //Li
    m1(&t)    
    
    //wang
    m()
}

所以各位同学在编程遇到此类问题一定要注意了.
那这些方法集之间到底是什么关系呢?这里借用了qyuhen在golang读书笔记的话,这里也

关于golang中方法的receiver为指针和不为指针的区别