Pass by value vs pass by reference
Let’s compare two functions to understand how pointers work:Key concepts
Pass by value
Pass by value
When you pass a variable to a function normally, Go creates a copy of that value. Changes made inside the function don’t affect the original variable.
Pass by reference with pointers
Pass by reference with pointers
When you pass a pointer, you’re passing the memory address of the variable. Changes made through the pointer affect the original variable.
Pointer syntax
Pointer syntax
&- Address-of operator:&igives you a pointer toi*- Dereference operator:*ptraccesses the value at the pointer*int- Type declaration: a pointer to an int
Common use cases
Avoiding copies
Pass large structs by pointer to avoid copying all the data
Modifying values
Allow functions to modify their arguments
Sharing state
Multiple parts of your program can reference the same data
Nil values
Pointers can be
nil, representing “no value”Go is a garbage collected language. You can safely return a pointer to a local variable — it will only be cleaned up when there are no active references to it.
Best practices
- Use pointers for large structs to avoid copying overhead
- Use pointers when you need to modify the argument
- Pass by value for simple types like int, bool, small structs
- Be careful with nil pointers — dereferencing a nil pointer causes a panic
Related topics
Structs
Learn about Go’s struct types
Methods
Methods with pointer receivers