V
Vel·ToolKit
Simple · Fast · Ready to use
EN
Chapter 9 of 20

Pointers

& and *, and when to use pointers

Address-of and Dereference

package main

import "fmt"

func main() {
    n := 42
    p := &n         // p is a *int
    fmt.Println(*p) // 42
    *p = 100
    fmt.Println(n) // 100
}

Pass by Value vs Pass by Pointer

All function parameters in Go are passed by value. Pass a pointer when you want a function to modify the caller's variable, or to avoid copying a large struct.

package main

import "fmt"

func grow(s *string) {
    *s += "!"
}

func main() {
    name := "go"
    grow(&name)
    fmt.Println(name) // go!
}

new and Zero-Value Pointers

new(T) returns a pointer to a zero-value T, equivalent to &T{}. Rarely used in practice.

package main

import "fmt"

func main() {
    p := new(int)
    *p = 5
    fmt.Println(*p)
}

No Pointer Arithmetic

Go does not support pointer arithmetic like p++; use a slice for bulk memory access.