(Newb Question) Why do you return the address of a struct when it is a struct literal in the function return argument?

xuanbao · 2017-03-27 23:00:05 · 383 次点击    
这是一个分享于 2017-03-27 23:00:05 的资源,其中的信息可能已经有所发展或是发生改变。

Here's an example of what I mean:

type person struct {
  name string
  age  int
}

func example() *person {
  return &person{"Frank", 15}
}

func main() {
  frank := example()
  fmt.Println(frank.name)
}

So what I mean is why would the function have *person (literal), when you are returning &person (address).

Edit:

Furthermore, when changed to this code:

func example() *person {
  p := &person{"Frank", 15}
  fmt.Printf("%x\n", p)
  fmt.Printf("%v\n", *p)
  return p
}

The output is:

&{4672616e6b f}
{Frank 15}
Frank

The pointer being returned CLEARLY does not equal the struct literal when using p, (effectively (&person{"Frank", 15}).


评论:

gtarget:

The syntax *person means a pointer to a person. When you return &person{"Frank", 15} you are saying return the address of the struct person you just created. A pointer is really just a variable holding the address of something else.

Franke123:

Got it! That makes sense now :) Thank you.

dmikalova:

Thanks, that cleared things up for me too.

DualRearWheels:

Quick tip: why would anyone use pointers anyway? 2 reasons:

  1. You can change struct using pointer from any place (loops, other functions etc.)

  2. Performance difference can be huge compared to not using pointer. With pointer program only copies address (4 or 8 bytes depending on your architecture). With struct as value program must copy much more (sum of all sizes of all fields, this can go to 100+ bytes depending on fields).

Franke123:

Thanks! As a pretty new programmer who learned JS first, pointers can be kind of confusing! But I do see the advantages.


入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

383 次点击  
加入收藏 微博
0 回复
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传