Pointers
Pointer is a variable which contains address of another values stored address.
Different values require different sizes of memory location, value is the boolean, but it still takes up a whole byte, that is because smallest representable amount of memory, and the other types takes up space their bit count divided by four; int32 -> 32 bits -> 4 bytes etc.
Slices, maps, interfaces, channels, and functions are impelemented using pointers. It’s common to pass channel to some other function, and defines their purpose, hence it’s pointer by default.
In modern computers, usually a pointer takes up 8 bytes of space, and zero value for a pointer is (the state where it’s not pointing to an address yet) is nil.
& is called the address operator, * is called the indirection operator, former exposes the address of a variable, while the latter exposes the value stored in the address. Calling the indirection operator on an address is called dereferencing.
Dereferencing a pointer (using indirection operator on it) that is nil, causes panic in the runtime, that’s why you need to make sure that the pointer is not nil
var x = 10
var addrX *int = &x
You may also create pointers via the built-in function called new, it returns the pointer to the zero value of the passed type
// Returns a pointer that points to 0, 0 because zero value of an int is 0
var x = new(int)
Defaulting to pointers blindly can create a lot of work for the garbage collector, you should use it sparingly, having such advantage for both primitive types and composite types is a strong feature of the languge.
Additionally, passing values by value guarantees the immutabilitiy, which makes the program easier to understand and track the data flow correctly.
Passed by Value or Reference
Other than the following types, everything passed by value by default
- Slices
- Maps
- Channels
- Interfaces
- Functions
You don’t need to specify a pointer type to make them pass by value, they are by default passed by pointer, and the remaining any other type is passed by value, i.e copied.