I'm trying to figure out how pointers work in Go and I think I'm starting to get it, but this is confusing me and I don't really know what to search for. Let's say I have the following function:
func createNode(nodeInfo string) *TreeNode {
return &TreeNode{info: nodeInfo}
}
I understand that the function is returning the memory address of the created struct instance, but how does the function signature say *TreeNode
? According to my understanding, the *
is used to dereference pointers to get the value itself, so what is happening here?
Also, here:
func zero(xPtr *int) {
*xPtr = 0
}
func main() {
x := 5
zero(&x)
}
The opposite is happening where the function is accepting an argument with the *
operator but the function itself is being called with &
operator.
The *
has 2 uses, one for variables and one for types:
*
on the left side of assignments, as in *ptr = val
sets the value the pointer is pointing to, while *
usually "retrieves" the value the pointer is pointing to.)&
on the other hand, can only be used for variables and gets the address of an object in memory.
In your examples, the return type *TreeNode
and the argument type *int
signify that you are returning/expecting a pointer, according to the use for types. In contrast, *xPtr = 0
dereferences the variable xPtr
.
To know which use is the correct one in your situation, you must make clear to yourself whether you are dealing with a type or a variable.
For a technical description, you can read the sections of the language specifications on Pointer types and Address operators.