Go pointers explained simply
Published on

Contents
A pointer in Go holds the memory address of a variable, not its value. You need one to change a variable inside a function, or to pass a large struct without copying it.
Syntax
| Symbol | Meaning | Example |
|---|---|---|
& | Address of | p := &x makes p a pointer to x |
* | Dereference | y := *p reads the value p points to |
*T | Pointer type | var p *int declares a pointer to an int |
An analogy
&xis like asking “What is the address of this house?”*pis like going to that address and looking inside.
Basic example
package main
import "fmt"
func main() {
x := 10
p := &x // p holds the address of x
fmt.Println("x =", x) // 10
fmt.Println("p =", p) // a memory address, like 0xc000018030
fmt.Println("*p =", *p) // 10, the value at that address
*p = 20 // change the value at that address
fmt.Println("x =", x) // 20
}
Change a value in a function
Go passes arguments by copy, so a function can’t change your variable. Pass a pointer to it instead, and the function changes the original.
func modify(val *int) {
*val = *val + 5 // change the value at that address
}
func main() {
x := 10
modify(&x) // pass the address of x
fmt.Println(x) // 15
}
Summary
&xgives the address ofx.*preads or changes the value atp.*Tis the type of a pointer toT, e.g.*int.