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.

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

报告相同问题?