Go

Pointers — When and Why

admin by @admin ADMIN
1d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Use pointers when you want to mutate the callee's value, share a large struct without copying, or distinguish "no value" via nil. Go has no pointer arithmetic — much safer than C.
Go
Raw
package main

import "fmt"

type Point struct {
    X, Y int
}

// Value receiver — caller\'s copy is unchanged
func (p Point) ScaleVal(n int) {
    p.X *= n
    p.Y *= n
}

// Pointer receiver — caller\'s value IS mutated
func (p *Point) ScalePtr(n int) {
    p.X *= n
    p.Y *= n
}

func main() {
    p := Point{X: 1, Y: 2}
    p.ScaleVal(10)
    fmt.Println(p)                            // {1 2}  — unchanged

    p.ScalePtr(10)                            // Go auto-addresses: &p
    fmt.Println(p)                            // {10 20}

    // & to take address, * to dereference
    n := 5
    ptr := &n
    *ptr = 99
    fmt.Println(n)                            // 99

    // Distinguish "no value" with a pointer
    var opt *Point                            // nil — meaning "absent"
    if opt == nil {
        fmt.Println("no point")
    }
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.