Pointers in golang.
Pointers in golang are strongly typed. A pointer to one type cannot be updated to point to a different type. Pointers are defined with *
: func(a *Address)
creates an address pointer. A pointer is a memory location that contains another memory address as a value. To access a value at that location, it needs to be referenced with &
. &a
will be an Address struct in the above.
Pointers are needed to share structs between functions. If the callee updates a struct it’s given, and the caller needs to see those updates, a pointer allows them to share the memory space the struct is in. If a struct is passed without pointers, its valuse get copied into a new struct in the callee and the two structs do not share changes. For particularly small structs, it is faster to copy the struct rather than set up the pointer. Pointers can be nil
and need to be checked before use. This is because stack allocation is cheap while heap allocation is expensive (re: copy versus pointer for small structs).