To pass a pointer to a function in Go, declare the parameter type with an asterisk (e.g., *int) and pass the address of the variable using the & operator. This allows the function to modify the original variable directly rather than working with a copy.
Here is a simple example showing the difference between passing by value and by pointer:
package main
import "fmt"
// Pass by value: changes are local to the function
func modifyValue(n int) {
n = 100
}
// Pass by pointer: changes affect the original variable
func modifyPointer(n *int) {
*n = 100
}
func main() {
x := 10
y := 10
modifyValue(x)
fmt.Println("After modifyValue:", x) // Output: 10 (unchanged)
modifyPointer(&y)
fmt.Println("After modifyPointer:", y) // Output: 100 (modified)
}
In this example, modifyValue receives a copy of x, so changes inside the function don't affect the original. In contrast, modifyPointer receives the memory address of y via &y, allowing it to update the original value.
You can also pass pointers to structs to avoid copying large data structures:
type User struct {
Name string
Age int
}
func updateAge(u *User) {
u.Age = 30
}
func main() {
user := User{Name: "Alice", Age: 25}
updateAge(&user)
fmt.Println(user.Age) // Output: 30
}
This pattern is essential when you need to mutate data, return multiple values (via pointers to output variables), or optimize performance by avoiding deep copies of large structs. Always ensure the pointer is not nil before dereferencing it to avoid runtime panics.