Go Passing Pointers to Functions – Modify Original Values Safely (2025 Guide)
Introduction – Why Pass Pointers to Functions in Go?
In Go, when you pass variables to functions, they are passed by value, meaning a copy is sent. To modify the original value, you must pass a pointer. This enables memory-efficient code, especially when working with large structs, arrays, or shared state.
In this section, you’ll learn:
- How to pass pointers to functions
- Modify variables and structs using pointers
- Avoid unnecessary copies
- Real-world examples and best practices
Basic Example – Pass Pointer to an int
func update(val *int) {
*val = 100
}
func main() {
x := 50
update(&x)
fmt.Println(x) // Output: 100
}
*val accesses the value at the memory address, allowing the function to modify x.
Modify Struct via Pointer
type Person struct {
Name string
Age int
}
func incrementAge(p *Person) {
p.Age++
}
func main() {
user := Person{"Alice", 30}
incrementAge(&user)
fmt.Println(user.Age) // Output: 31
}
Passing a pointer to a struct avoids copying and allows field updates directly.
Pass Pointers to Arrays
func double(arr *[3]int) {
for i := range arr {
arr[i] *= 2
}
}
func main() {
a := [3]int{1, 2, 3}
double(&a)
fmt.Println(a) // Output: [2 4 6]
}
Use *[N]Type to pass arrays by reference for in-place modification.
Real-World Use Case – In-Place Swap
func swap(a, b *int) {
*a, *b = *b, *a
}
func main() {
x, y := 1, 2
swap(&x, &y)
fmt.Println(x, y) // Output: 2 1
}
Pointers make it easy to swap, modify, or transform values in-place.
When Should You Use Pointers?
| Use Case | Use Pointer? |
|---|---|
| Modify original variable | Yes |
| Pass large structs (avoid copy) | Yes |
| Read-only values | No |
| Slices (already references) | Not needed |
Pitfalls to Avoid
- Don’t forget to dereference with
* - Avoid nil pointer dereference (
*nil) - Always check if pointer is valid before use
Summary – Recap & Next Steps
Passing pointers to functions allows you to modify original values, save memory, and write efficient, idiomatic Go code. It’s a core skill for working with structs, large data, and memory-efficient logic.
Key Takeaways:
- Use
*Tto declare pointer parameters - Use
&varto pass a variable’s address - Use
*paramto access or change the original value - Prefer pointers for performance and in-place modifications
Next: Learn how Go Interfaces and Methods work with pointer receivers vs value receivers.
FAQs – Go Passing Pointers to Functions
Why use pointers instead of values in Go?
To modify the original variable and avoid copying large data.
What is *T and &var in Go?
*T declares a pointer to type T; &var returns the address of a variable.
Do slices need to be passed as pointers?
No. Slices are already reference types.
Can I pass a nil pointer to a function?
Yes, but you must handle it carefully to avoid panics.
How do I access the value inside a pointer?
Use the dereference operator *, e.g., *p.
Share Now :
