Skip to content

Go Pointers

A pointer is a variable that stores the memory address of another variable. Instead of holding a value (like 42), it holds a location (like 0xc0000120b0).

Basic Syntax

  • &: The "address of" operator. It gives you the memory address of a variable.
  • *: The "dereference" operator. It allows you to access or change the value at the address a pointer is holding.
package main

import "fmt"

func main() {
    i := 42
    p := &i // p points to i

    fmt.Println(p)  // Prints the memory address (e.g., 0xc0000120b0)
    fmt.Println(*p) // Prints the value at that address (42)

    *p = 21         // Changes the value of i through the pointer
    fmt.Println(i)  // Prints 21
}

Why use Pointers?

  1. Efficiency: Passing a pointer to a large struct is much faster than copying the entire struct.
  2. Modification: If you want a function to modify a variable from the outside, you must pass a pointer.

Comparison: Value vs Pointer

package main

import "fmt"

// This function receives a COPY (value remains unchanged outside)
func zeroval(ival int) {
    ival = 0
}

// This function receives a POINTER (modifies the actual variable)
func zeroptr(iptr *int) {
    *iptr = 0
}

func main() {
    i := 1
    zeroval(i)
    fmt.Println(i) // 1

    zeroptr(&i)
    fmt.Println(i) // 0
}

Important Notes

  • Nil Pointers: The "zero value" of a pointer is nil. Trying to dereference a nil pointer will cause a crash (panic).
  • No Pointer Arithmetic: Unlike C, Go does not allow you to add or subtract from pointers (e.g., p++ is not allowed).