drbi19093 2016-02-14 05:06
浏览 66
已采纳

Golang:创建新实例的3种方法有什么区别? (初学者)

I'm new to Golang and from what I've learned so far there are 3 different ways to new up a struct:

a := MyStruct {}  // plain by value style. Is that what this is called?
b := new(MyStruct) // using new
c := &MyStruct {} // using a reference

Example

I'm not clear as to the actual differences between each of these other then I've found that I have to add a reference & symbol when printing the memory address of the object like this fmt.Printf("%p ", &a) when using the "plain" style vs fmt.Printf("%p ", b) for the "new" and "reference" styles. My assumption is that this is because using the "plain" style allocates memory differently but this is just a guess.

It appears that using the "new" and "reference" styles are equivalent options so choosing between those to is a stylistic decision? Is there an idiomatic preference in this language as to which method I should use? Are there other styles that I've not discovered yet?

  • 写回答

1条回答 默认 最新

  • drz49609 2016-02-14 05:29
    关注

    The Go Programming Language Specification

    Composite literals

    Allocation

    Variable declarations

    Short variable declarations

    a := MyStruct {}  
    b := new(MyStruct) 
    c := &MyStruct {} 
    

    a is a composite literal value. b is a pointer to a zero value for the type. c is a pointer to a composite literal value. a and c are very common. b is uncommon, in most cases, c is used.

    Take the Tour of Go for examples.

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

报告相同问题?

悬赏问题

  • ¥15 slaris 系统断电后,重新开机后一直自动重启
  • ¥15 51寻迹小车定点寻迹
  • ¥15 谁能帮我看看这拒稿理由啥意思啊阿啊
  • ¥15 关于vue2中methods使用call修改this指向的问题
  • ¥15 idea自动补全键位冲突
  • ¥15 请教一下写代码,代码好难
  • ¥15 iis10中如何阻止别人网站重定向到我的网站
  • ¥15 滑块验证码移动速度不一致问题
  • ¥15 Utunbu中vscode下cern root工作台中写的程序root的头文件无法包含
  • ¥15 麒麟V10桌面版SP1如何配置bonding