~/Go Pointers Quick Guide

Feb 14, 2022


A pointer in Go is a variable that stores the memory address of another variable. Using pointers helps efficiently manage memory and allows you to pass references instead of copying data.

Define a pointer with an asterisk before the type:

1
var p *int

Assign the address of a variable using the ampersand:

1
2
x := 42
p = &x

Dereference the pointer to access or change the value:

1
2
fmt.Println(*p) // displays 42
*p = 21         // changes x to 21

Passing a pointer to a function allows the function to modify the value:

1
2
3
func setVal(ptr *int) {
    *ptr = 5
}

Pointers are nil by default until assigned. Check the Go spec on pointers for more details.

Pointers are safe in Go due to garbage collection and absence of pointer arithmetic. This keeps code efficient and prevents memory leaks.

Tags: [golang] [pointers]