GGistDev

Pointers in Go

Pointers hold memory addresses. Use them to share/mutate data and avoid copying large values.

Address and dereference

Use & to take an address and * to dereference. Go does not support pointer arithmetic; this keeps code safe and simple.

x := 10
px := &x   // address-of
*px = 20   // dereference and set

Functions with pointers

Pass pointers to mutate arguments or to avoid copying large structs. Returning pointers to local variables is safe in Go; the compiler moves them to the heap when needed.

type Box struct{ W, H int }

func Scale(b *Box, k int) { // mutate
    b.W *= k; b.H *= k
}

func main() {
    b := Box{2, 3}
    Scale(&b, 2)
}

Methods and receivers

Choose pointer receivers when methods need to mutate the receiver or when copying would be expensive. Value receivers are fine for small, immutable types.

type Counter int
func (c *Counter) Inc() { *c++ }     // pointer receiver mutates
func (c Counter) Val() int { return int(c) } // value receiver copies

Nil pointers

Always consider nil checks before dereferencing pointers. Zero value of a pointer type is nil.

var p *int
if p == nil { /* initialize or guard */ }

When to use pointers

  • To modify a value inside a function or method
  • To avoid copying large structs
  • To share state between functions

When to avoid

  • For small, immutable values; prefer value semantics
  • When ownership/lifetime is unclear
  • For synchronization: prefer channels/mutexes over pointer tricks

Summary

  • & to get address, * to dereference
  • Pointer receivers mutate; value receivers work on copies
  • Check for nil as needed