doujiao9574 2014-06-10 02:29
浏览 39
已采纳

golang方法指向接收者的指针

I have the following struct and :

type Person struct {
    Name    string
}


steve := Person{Name: "Steve"}

Can you explain how the following 2 methods (one without the pointer and one with in the receiver) both are able to print the p.Name?

func (p *Person) Yell() {
    fmt.Println("Hi, my name is", p.Name)
}

func (p Person) Yell(){
    fmt.Println("YELLING MY NAME IS", p.Name)
}

steve.Yell()

Wouldn't the Name not exist when pointing straight to the Person (not the instance steve?)

  • 写回答

1条回答 默认 最新

  • doumeng9188 2014-06-10 02:36
    关注

    Both point to the instance, however (p Person) points to a new copy every time you call the function, where (p *Person) will always point to the same instance.

    Check this example :

    func (p Person) Copy() {
        p.Name = "Copy"
    }
    
    func (p *Person) Ptr() {
        p.Name = "Ptr"
    }
    
    func main() {
        p1, p2 := Person{"Steve"}, Person{"Mike"}
        p1.Copy()
        p2.Ptr()
        fmt.Println("copy", p1.Name)
        fmt.Println("ptr", p2.Name)
    }
    

    Also read Effective Go, it's a great resource to the language.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 webAPI接口返回值判断
  • ¥15 自动化测试 UI Automtion
  • ¥20 关于#深度学习#的问题:2708)输出:邻接矩阵A 或者 节点索引方式:通过随机游走或者其他方式,保持节点连接类似下图(语言-python)
  • ¥15 win2012 iscsi ipsec
  • ¥15 封装的 matplotlib animation 不显示图像
  • ¥15 python摄像头画面无法显示
  • ¥15 关于#3d#的问题:d标定算法(语言-python)
  • ¥15 cve,cnnvd漏洞扫描工具推荐
  • ¥15 图像超分real-esrgan网络自己训练模型遇到问题
  • ¥15 如何构建全国统一的物流管理平台?