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
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?
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.