Skip to content

Pointers

A pointer holds the memory address of a value. Use *T for a pointer to a T, and & to get the address. Go has no pointer arithmetic (except via unsafe).

Pass by value vs by reference.

package main
import "fmt"
func zeroVal(x int) {
x = 0
}
func zeroPtr(x *int) {
*x = 0
}
func main() {
a := 42
zeroVal(a)
fmt.Println(a) // still 42
zeroPtr(&a)
fmt.Println(a) // now 0
// nil pointers
var p *int
if p == nil {
fmt.Println("p is nil")
}
}
Terminal window
42
0
p is nil