Vladyslav Krylasov's website

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

SymbolMeaningExample
&Address ofp := &x makes p a pointer to x
*Dereferencey := *p reads the value p points to
*TPointer typevar p *int declares a pointer to an int

An analogy

  • &x is like asking “What is the address of this house?”
  • *p is 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

  • &x gives the address of x.
  • *p reads or changes the value at p.
  • *T is the type of a pointer to T, e.g. *int.