Considering the following Go struct:
type Person struct {
Name string
Age int
Country string
}
I have encountered numerious times the following use:
p := &Person{"Adam", 33, "Argentina"}
Yet I can not see the point in pointing to a struct value, and I wonder, how does it differ from:
n := &999 // Error
My questions are:
How is it even possible to point to a value, even if it is a struct or array and not a primitive like a string or int? Strange enough, the following doesn't contribute to my understanding:
fmt.Println(p, &p) // outputs: &{Adam 33 Argentina} 0xc042084018
Why would a programmer want to declare a struct instance by a pointer? What could you achieve doing so?
&Person{}
is a language "construct", it's part of the spec: it allocates a new variable ofPerson
type, and provides you the address of that anonymous variable.Spec: Composite literals:
Also: Spec: Variables:
&999
is not allowed by the language spec. The possible operands of the address operators are listed in the Spec: Address operators:p := Person{}
creates a new variablep
whose type will bePerson
.p := &Person{}
creates a new variable whose type will be*Person
.See possible duplicate: How do I do a literal *int64 in Go?
When you print the values with the
fmt
package, it has certain rules how to print values of different types:When you use
fmt.Println()
, the default formatting rules will be applied, which for a value of type*int
is the%p
verb, which will print the memory address in hexadecimal format, but for a pointer to struct it prints the struct value prepended with an&
sign (&{}
). You can read more about it in related question: Difference between golang pointersIf you want to print the pointed value, dereference the pointer and pass the pointed value, e.g.:
As to why to create a pointer to a value (and not a value), see these related questions:
Pointers vs. values in parameters and return values
Why should constructor of Go return address?
Go, X does not implement Y (... method has a pointer receiver)