Pass by Reference
By default, Go passes variables to functions by value, meaning the function receives a copy of the data. Pointers allow us to pass variables by reference.
Value vs. Reference
// Pass by Value (Copy)
func incrementValue(x int) {
x++ // only increments the local copy
}
// Pass by Reference (Original)
func incrementPointer(x *int) {
*x++ // increments the original value
}
Pointer Fields in Structs
When working with a pointer to a struct, Go provides syntactic sugar to access fields directly using the dot operator. You don’t need to manually dereference the struct first.
type User struct {
Name string
}
func updateName(u *User) {
// Both are valid, but the second is preferred
(*u).Name = "Bob"
u.Name = "Alice"
}
When to use?
Use pointers when:
- You need to modify the original variable.
- The data structure is very large, and you want to avoid the cost of copying it (though this is often less of an issue than beginners expect).