Go Pointers
A pointer is a variable that stores the memory address of another variable. Instead of holding a value (like 42), it holds a location (like 0xc0000120b0).
Basic Syntax
&: The "address of" operator. It gives you the memory address of a variable.*: The "dereference" operator. It allows you to access or change the value at the address a pointer is holding.
Why use Pointers?
- Efficiency: Passing a pointer to a large struct is much faster than copying the entire struct.
- Modification: If you want a function to modify a variable from the outside, you must pass a pointer.
Comparison: Value vs Pointer
Important Notes
- Nil Pointers: The "zero value" of a pointer is
nil. Trying to dereference anilpointer will cause a crash (panic). - No Pointer Arithmetic: Unlike C, Go does not allow you to add or subtract from pointers (e.g.,
p++is not allowed).