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 深度学习残差模块模型
  • ¥20 两个不同Subnet的点对点连接
  • ¥50 怎么判断同步时序逻辑电路和异步时序逻辑电路
  • ¥15 差动电流二次谐波的含量Matlab计算
  • ¥15 Can/caned 总线错误问题,错误显示控制器要发1,结果总线检测到0
  • ¥15 C#如何调用串口数据
  • ¥15 MATLAB与单片机串口通信
  • ¥15 L76k模块的GPS的使用
  • ¥15 请帮我看一看数电项目如何设计
  • ¥23 (标签-bug|关键词-密码错误加密)