Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Go Structs and Pointers: Value vs Pointer Receivers, Embedding, and Memory

Value and pointer receivers, shallow copies, addressability, embedding, and struct layout: the rules that decide when a method mutates, when a copy diverges, and why field order changes size.

~5 min readGo
#Go#Data Structures#Backend
Go struct blocks contrasted with pointer addresses and value copies

A Go struct is a fixed sequence of typed fields, and every assignment, argument pass, and range iteration over one copies all of its bytes. That single rule explains the receiver question: a value receiver works on a copy and cannot change the original, while a pointer receiver works on the value stored at an address. The second rule explains most of the surprises: the copy is shallow, so a struct holding a slice, map, or pointer shares that backing data with the original even though the struct itself was copied.

Quick Summary

  • Struct assignment copies. b := a gives b its own fields, but any slice, map, or pointer inside still refers to the same underlying data.
  • Value receivers copy the receiver; pointer receivers alias it. Choose pointer when the method mutates, when the struct is large, or when it holds a sync.Mutex — and keep the choice consistent across the type.
  • The method set of T contains only value-receiver methods; the method set of *T contains both. That is why T may fail to satisfy an interface that *T satisfies.
  • Go takes the address automatically only for addressable operands. Map elements and function results are not addressable, so pointer methods cannot be called on them.
  • Embedding promotes fields and methods of the embedded type. It is composition, not inheritance: the outer type does not become the inner type.
  • Field order affects size. Grouping fields from largest alignment to smallest can cut padding; unsafe.Sizeof and unsafe.Offsetof show the actual layout.
  • A struct is comparable only if every field is comparable. Slices, maps, and funcs make == a compile error, and a sync.Mutex field makes copying a struct a go vet error.

Basic syntax and type signatures

go
type Account struct { mu sync.Mutex // cannot be copied after first use Owner string Balance int64 tags []string // unexported, shared on copy } // Pointer receiver: mutates the original and does not copy the struct. func (a *Account) Deposit(amount int64) { a.mu.Lock() defer a.mu.Unlock() a.Balance += amount } // Value receiver: reads a copy. Safe for small, immutable data. func (a Account) Summary() string { return fmt.Sprintf("%s: %d", a.Owner, a.Balance) } // Embedding promotes the inner type's fields and methods. type Audited struct { *Account Auditor string } func main() { acct := &Account{Owner: "ada", Balance: 10} acct.Deposit(5) fmt.Println(acct.Summary()) // "ada: 15" a := Audited{Account: acct, Auditor: "ops"} a.Deposit(1) // promoted: calls (*Account).Deposit fmt.Println(a.Balance) // 16, promoted field }

Embedding a pointer (*Account) puts every method of *Account in the method set of both Audited and *Audited. Embedding a value (Account) gives Audited only the value-receiver methods, and *Audited both — the same rule as ordinary receivers, applied one level down.

Receivers side by side

func (a T) M()func (a *T) M()
Copies the receiveryes, whole structno, one pointer word
Can mutate fieldsno, changes are discardedyes
In method set of Tyesno
In method set of *Tyesyes
Callable on a non-addressable valueyesno (compile error)
Callable on a nil pointercrashes on field accessworks if the method does not dereference
Right whensmall value, immutable, or a map/slice-like typemutation, large struct, mutex, or consistency

The last row of the nil column is a real technique, not a curiosity: a method with a nil-check at its top (if a == nil { return defaultAccount }) makes a nil *Account a valid zero value, and json encoders rely on the same property.

Practical edge cases and deep dives

1. What a copy actually copies

go
type Batch struct { Name string Items []int Index map[string]int next *Batch } func mutate(b Batch) { // receives a copy of the struct header b.Name = "changed" // original unaffected b.Items[0] = 99 // original slice element changed: shared array b.Items = append(b.Items, 4) // original len unaffected, maybe shared array b.Index["x"] = 1 // original map changed: maps are references } func main() { orig := Batch{Name: "a", Items: []int{1, 2, 3}, Index: map[string]int{}} mutate(orig) fmt.Println(orig.Name, orig.Items, orig.Index) // a [99 2 3] map[x:1] }

Items[0] = 99 is visible to the caller because the slice header was copied but the array it points to was not. append is the subtle one: if the slice had spare capacity, the append writes into the shared array and the caller's later append can overwrite it; if it did not, append allocates and the copy diverges. The rule to hold onto is that Go has value semantics for the struct and reference semantics for what the struct points at, and the compiler will not tell you which of your fields fall on which side.

The same applies to interfaces: passing a struct to a function that takes any boxes a copy, which is why mutating a value-receiver method through an interface has no effect.

go
type Counter struct{ n int } func (c Counter) Inc() { c.n++ } // no effect on the caller's value func main() { c := Counter{} var i interface{ Inc() } = c i.Inc() fmt.Println(c.n) // 0 }

2. Addressability, and why the pointer method will not compile

go
type Point struct{ X, Y int } func (p *Point) Scale(f int) { p.X *= f; p.Y *= f } func main() { var p Point p.Scale(2) // ok: p is addressable points := []Point{{1, 2}} points[0].Scale(2) // ok: slice elements are addressable m := map[string]Point{"a": {1, 2}} // m["a"].Scale(2) // compile error: cannot call pointer method on m["a"] // Point{1, 2}.Scale(2) // compile error: cannot call pointer method on Point literal // Correct form for the map case: v := m["a"] v.Scale(2) m["a"] = v // write the modified copy back }

A slice element is addressable because the backing array lives at a stable address; a map element is not, because the map may rehash and move its buckets, so the address you took could be invalidated by the very next insert. That is a language rule, not a compiler limitation, and it is why maps of structs are usually replaced with maps of pointers when the values are mutated.

3. Layout, padding, and the cost of field order

go
type Padded struct { A bool // offset 0, size 1, then 7 bytes of padding B int64 // offset 8 C bool // offset 16, then 7 bytes of padding } // Sizeof = 24 type Packed struct { B int64 // offset 0 A bool // offset 8 C bool // offset 9, then 6 bytes of padding } // Sizeof = 16 func main() { fmt.Println(unsafe.Sizeof(Padded{}), unsafe.Sizeof(Packed{})) // 24 16 fmt.Println(unsafe.Offsetof(Padded{}.C)) // 16 }

Each field must start at an offset that is a multiple of its alignment, so a bool before an int64 forces seven bytes of padding and the same happens after it. Reordering fields largest to smallest turns 24 bytes into 16 without changing behaviour or marshalling output, because encoding/json and fmt use field names, not offsets. The same check pays off in hot data structures: a slice of a million such structs is 8 MB smaller after reordering, and the bytes are then packed the way the cache likes them.

Slices and strings are already headers: a slice is a pointer, a length, and a capacity (24 bytes on a 64-bit platform), a string is a pointer and a length (16 bytes). Copying them copies three or two words, never the data.

4. Embedding versus named fields, and the mutex it saves you from

go
type Logger struct{ prefix string } func (l Logger) Log(msg string) { fmt.Println(l.prefix + msg) } type Service struct { Logger // embedded: Log is promoted, `s.Log(...)` works // logger Logger // named: `s.logger.Log(...)`, not part of Service's method set Name string } func main() { s := Service{Logger: Logger{prefix: "[svc] "}, Name: "api"} s.Log("started") // promoted method }

Embedding is the right tool when the outer type genuinely is the inner capability (a service that logs, a handler that reads) and the wrong tool when it merely contains one — the promoted method then leaks onto the public API and locks in the field name as a selector. The most expensive version of that mistake is embedding sync.Mutex directly, which exports Lock and Unlock and makes them part of the type's interface; a named mu sync.Mutex field keeps them private and stops being promoted into any interface the outer type satisfies.

go
type SafeCounter struct { mu sync.Mutex // named, not embedded n int } func (c *SafeCounter) Inc() { c.mu.Lock() defer c.mu.Unlock() c.n++ } // go vet: "Inc passes lock by value: SafeCounter contains sync.Mutex" // func (c SafeCounter) Inc() { ... }

Common mistakes and compiler errors

ErrorMessageCauseFix
compilecannot call pointer method on m[k]mutating a map element in placecopy out, mutate, assign back
compilecannot take the address of p& on a composite literal inside a call, or a constantassign to a variable first
compileinvalid operation: a == b (struct containing []int cannot be compared)== on a struct with an uncomparable fieldcompare a key field, or reflect.DeepEqual
compileambiguous selector s.Nametwo embedded types at the same depth provide Namequalify with the type name
compilecannot use s (variable of type S) as I value: method M has pointer receivervalue passed where *S is neededpass &s
vetpasses lock by valuea struct containing sync.Mutex copied or passed by valueuse pointer receivers and *T slices
runtimeinvalid memory address or nil pointer dereferencefield access through a nil pointerguard at the top of the method
runtimeappend result lostappend called without assigning its return values = append(s, v)

One rule covers the compile-time half: a pointer is required wherever the value must be changed in place or must not be copied, and Go's addressability rules decide whether & can be inserted for you. When the compiler refuses with "cannot call pointer method", the fix is almost always to store the value in a variable — which is also the moment to ask whether a slice of pointers, or a pointer-valued field, was the better design in the first place.

Try matching browser tools

All tools

Small utilities that fit Go work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Go guides

More in Go

All Go guides

The guides filed next to this one in Go, in library order.