I was learning golang, and as I was going through the chapter that describes Structures, I came across different ways to initialize structures.
p1 := passport{}
There is variable that holds the data yet. You can dereference the pointer using *pointerp2
, and even assign it that to a variable (p2 := pointerp2
), but this variable would be a copy of the data. That is, modifying one no longer affects the other (http://play.golang.org/p/9yRYbyvG8q).
new
tends to be less popular, especially with regard to structs. A good discussion of its purpose (hint: it came first) and use cases can be found at https://softwareengineering.stackexchange.com/a/216582.
Edit: Also, p1
is not really a different kind of initialization from p3
, but instead of assigning a value to any of the type's fields they are initialized to their zero value (""
for string
, nil
for []byte
). The same would happen for any omitted fields:
p4 := passport{
Name: "Scott",
Surname: "Adam",
}
In this case, p4.Photo
and p4.DateOfBirth
would still be zero-valued (nil
and ""
respectively). The passport{}
case it just one where all the fields are omitted.