- Reference: TDD, Go Chinese Docs,
Definition
Every var has memory address and value, Pointer is the variable that store the address as its value. In Go language, &
means toke address operation, while *
means get the value from address operation. Pointer is a kind of variable that store the address of corresponding variable.
Syntax
1 | ptr := &v |
Example:
1 | func main() { |
Token Address: &
get pointer
Get the value of pointer: *
get value of pointer infered
Pointers let us point to some values and then let us change them.
Go copies values when you pass them to functions/methods, so if you’re writing a function that needs to mutate state you’ll need it to take a pointer to the thing you want to change.
The fact that Go takes a copy of values is useful a lot of the time but sometimes you won’t want your system to make a copy of something, in which case you need to pass a reference. Examples include referencing very large data structures or things where only one instance is necessary (like database connection pools).
Pointers can be nil
When a function returns a pointer to something, you need to make sure you check if it’s nil or you might raise a runtime exception - the compiler won’t help you here.
Useful for when you want to describe a value that could be missing