donkey199024 2015-12-29 01:43
浏览 22
已采纳

访问结构字段时Golang结构文字和指针之间的区别

I don't understand the difference between a struct literal and a struct pointer when accessing struct fields. Is there any different internal behavior ?

type Person struct {
    Name string
}

p := &Person{Name: "Alice"}
u := Person{Name: "Bob"}

fmt.Println(p.Name)  // any difference ?
fmt.Println(u.Name)  // any difference ?

I searched for this but posts I found all explain about difference between value & pointer, or "passing a value" vs "passing a pointer" to a method. They are not what I want to know.

  • 写回答

1条回答 默认 最新

  • du2229 2015-12-29 01:47
    关注

    u is a variable of type Person. p is a variable of type "pointer to Person", and it is initialized with the address of an anonymous ("temporary") object. The expression p.Name uses auto-dereferencing of pointers and is equivalent to (*p).Name. The object that p points to lives as long as p points to it and may thereafter be destroyed by Go's non-deterministic memory manager.

    Both p.Name and u.Name are expressions of type string, and they're not "passed by pointer" since their address is not taken in the call. In the case of fmt.Println, the value is actually passed "by interface" using Go's structural subtyping form of ad-hoc polymorphism.

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

报告相同问题?

悬赏问题

  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)