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.

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 := agivesbits 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
Tcontains only value-receiver methods; the method set of*Tcontains both. That is whyTmay fail to satisfy an interface that*Tsatisfies. - 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.Sizeofandunsafe.Offsetofshow the actual layout. - A struct is comparable only if every field is comparable. Slices, maps, and funcs make
==a compile error, and async.Mutexfield makes copying a struct ago veterror.
Basic syntax and type signatures
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 receiver | yes, whole struct | no, one pointer word |
| Can mutate fields | no, changes are discarded | yes |
In method set of T | yes | no |
In method set of *T | yes | yes |
| Callable on a non-addressable value | yes | no (compile error) |
| Callable on a nil pointer | crashes on field access | works if the method does not dereference |
| Right when | small value, immutable, or a map/slice-like type | mutation, 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
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.
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
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
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
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.
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
| Error | Message | Cause | Fix |
|---|---|---|---|
| compile | cannot call pointer method on m[k] | mutating a map element in place | copy out, mutate, assign back |
| compile | cannot take the address of p | & on a composite literal inside a call, or a constant | assign to a variable first |
| compile | invalid operation: a == b (struct containing []int cannot be compared) | == on a struct with an uncomparable field | compare a key field, or reflect.DeepEqual |
| compile | ambiguous selector s.Name | two embedded types at the same depth provide Name | qualify with the type name |
| compile | cannot use s (variable of type S) as I value: method M has pointer receiver | value passed where *S is needed | pass &s |
| vet | passes lock by value | a struct containing sync.Mutex copied or passed by value | use pointer receivers and *T slices |
| runtime | invalid memory address or nil pointer dereference | field access through a nil pointer | guard at the top of the method |
| runtime | append result lost | append called without assigning its return value | s = 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 toolsSmall utilities that fit Go work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Go guides
All Go guidesGo iota: Enumerations, Bitmask Flags, and Constant Expressions
How iota advances per const line, typed enums with gaps, bit flags with 1 << iota, and the unit scale pattern that shifts with one blank line.
Go JSON: Marshaling, Unmarshaling, Struct Tags, and Custom Parsers
Struct tags, omitempty that skips false and zero, custom marshalers without recursion, RawMessage for tagged unions, and float64 precision loss.
Go Strings, Runes, and Bytes: UTF-8 Encoding, Conversion, and Memory
Bytes versus runes, len that counts bytes, slicing that splits characters, Builder for linear concatenation, and normalization the standard library omits.
Go select Statement: Non-Blocking Operations, Timeouts, and Nil Channels
Random choice among ready cases, non-blocking polls with default, nil channels that disable a case, timer reuse, and labeled breaks out of a loop.
More in Go
All Go guidesThe guides filed next to this one in Go, in library order.