Types and values
Go has one rule for passing data: it copies. Most surprises in this sheet come from what a copy shares and what it does not. Each output below is from a real run.
- 1Every assignment and every call copies. A copy of a pointer, slice or map still reaches the same data.
- 2Design the zero value to work. A nil slice, an unlocked mutex and an empty Buffer need no constructor.
- 3A pointer method needs an address. A value in an interface has none, so T does not satisfy it.
- 4Constants are exact until they get a type. Conversions lose bits with no error, and assertions check at run time.
package main
import "fmt"
type Counter struct{ n int }
func (c Counter) Inc()1 { c.n++2 }
func main() {
var c Counter
for range 3 {
c.Inc()3
}
fmt.Println("count:", c.n)
}- 1A value receiver: c is a new copy on each call.
- 2This changes the copy. The copy dies when Inc returns.
- 3Valid Go. With a pointer receiver, this same line writes (&c).Inc().
| receiver | recorded output | status |
|---|---|---|
| (c Counter) | count: 0 | Write lost |
| (c *Counter) | count: 3 | Approved |
- The call site looks the same in both programs. Only the receiver differs.
- The same rule explains range values, map reads and function arguments: each one is a copy.
- A test on the return value of Inc finds nothing, because Inc has no return value.
A value receiver works on a copy, so the write is lost. A method that changes state takes a pointer.
- Each field sits at a multiple of its alignment. The struct size is a multiple of its largest alignment.
- Over 1,000,000 values, the second order saves 8 MB.
Field order sets the padding. I sort by size only for a type that exists in millions.
| type | bytes |
|---|---|
| int | 8 |
| *T | 8 |
| map | 8 |
| chan | 8 |
| func | 8 |
| string | 16 |
| any | 16 |
| []T | 24 |
| struct{} | 0 |
| [0]int | 0 |
A slice is 3 words, a string and an interface are 2, and a map is 1. Copying each one is cheap.
| type | zero value | operation | result | status |
|---|---|---|---|---|
| []int | []int(nil) | len(s), range, append | [1] | Safe |
| []int | []int(nil) | s[0] | runtime error: index out of range [0] with length 0 | Panics |
| map[string]int | map[string]int(nil) | m["a"], len, range, delete | 0 | Safe |
| map[string]int | map[string]int(nil) | m["a"] = 1 | assignment to entry in nil map | Panics |
| *Person | (*types.Person)(nil) | p == nil | true | Safe |
| *Person | (*types.Person)(nil) | p.Age | runtime error: invalid memory address or nil pointer dereference | Panics |
| func() | nil | f() | runtime error: invalid memory address or nil pointer dereference | Panics |
| fmt.Stringer | <nil> | i.String() | runtime error: invalid memory address or nil pointer dereference | Panics |
| sync.Mutex | unlocked | mu.TryLock() | true | Safe |
| bytes.Buffer | empty | buf.WriteString | a | Safe |
| strings.Builder | empty | sb.WriteString | a | Safe |
| time.Time | 0001-01-01 00:00:00 +0000 UTC | t.IsZero() | true | Safe |
A receive or send on a nil channel blocks forever. See G11 for the channel table.
Reads on a nil slice or a nil map are safe. Writes to a nil map, and calls through nil, panic.
// Tally counts by name. Its zero value is ready to use.
type Tally struct {
mu sync.Mutex1
counts map[string]int
}
func (t *Tally) Add(name string, n int) {
t.mu.Lock()
defer t.mu.Unlock()
if t.counts == nil {2
t.counts = make(map[string]int)
}
t.counts[name] += n
}
// Get reads a nil map safely, so it needs no check.
func (t *Tally) Get(name string) int {
t.mu.Lock()
defer t.mu.Unlock()
return t.counts[name]3
}- 1Not a pointer. The zero Mutex is unlocked, and a value field needs no constructor.
- 2A lazy make, under the lock. A nil map panics on a write.
- 3A nil map returns 0 here, so Get needs no check.
Nil and empty slices differ in one place: JSON. Recorded: {"items":null} and {"items":[]}.
My type works with var t Tally. The mutex needs no setup, and the map appears on the first write.
| the type | receiver |
|---|---|
| Has a method that changes it | Pointer |
| Holds a Mutex or a WaitGroup | Pointer |
| Is large: 1 KB by value costs 15.5 ns, by pointer 1.2 ns | Pointer |
| Is small and immutable, such as time.Time | Value |
| Is a map, a func or a chan | Value |
| Mixes both kinds across methods | Not approved |
| Uses a pointer only for speed, at 64 B or less | Measure first |
go vet reports a copied Mutex. The sync documentation forbids a copy after first use.
I pick one receiver kind per type. A mutex or a mutation means pointer, for every method on that type.
| method on | T in interface | *T in interface | variable x.M() | m[k].M() |
|---|---|---|---|---|
| (t T) | Yes | Yes | Yes | Yes |
| (t *T) | No | Yes | Yes | No |
- x.M() works on a variable because the compiler writes (&x).M(). A variable is addressable.
- A map element and a function result are not addressable, so the call fails. A slice element is addressable.
cannot use T{…} (value of struct type T) as fmt.Stringer value in variable
declaration: T does not implement fmt.Stringer (method String has pointer
receiver)
cannot call pointer method Inc on TThe method set of T has only value methods. A value in an interface is an unnamed copy, so it cannot give a pointer method an address.
// Money is small and immutable, so it uses value receivers.
type Money struct {
Cents int64
Currency string
}
func (m Money) Add(o Money) Money {1
m.Cents += o.Cents
return m
}
func (m Money) String() string {
return fmt.Sprintf("%d.%02d %s", m.Cents/100, m.Cents%100, m.Currency)
}
// Account holds a mutex and changes, so every method uses a pointer.
type Account struct {
mu sync.Mutex
balance Money
}
func (a *Account) Deposit(m Money) {2
a.mu.Lock()
defer a.mu.Unlock()
a.balance = a.balance.Add(m)
}
func (a *Account) Balance() Money {
a.mu.Lock()
defer a.mu.Unlock()
return a.balance
}- 1The copy is safe to change. The result carries the sum, and the caller keeps its value.
- 2A value receiver would copy the lock and lose the write.
Money is a value: Add returns a new one. Account holds a lock, so it is always behind a pointer.
type Base struct{ ID string }
func (b Base) Kind() string { return "base" }
// Label calls Base.Kind, whatever type embeds Base.
func (b Base) Label() string1 { return b.Kind() + ":" + b.ID }
type User struct {
Base
Email string
}
// Kind hides Base.Kind for callers that hold a User.
func (u User) Kind() string3 { return "user" }
// Label must be written again to use the new Kind.
func (u User) Label() string { return u.Kind() + ":" + u.ID }- 1The receiver is a Base. This call to Kind always means Base.Kind.
- 2The field name is Base. Its fields and methods are promoted to User.
- 3The shallower name wins. u.Base.Kind() still reaches the inner one.
- Two embedded types with one field name compile, but using that name does not.
- Do not embed sync.Mutex in an exported struct. Lock becomes part of its API.
Embedding is delegation, not inheritance. An inner method calls inner methods and never reaches the outer type.
type Status int
const (
StatusUnknown Status = iota1 // The zero value means "not set".
StatusOpen
StatusPaid
StatusVoid
)
var statusNames = [...]string{"unknown", "open", "paid", "void"}
func (s Status) String() string {
if s < 0 || int(s) >= len(statusNames) {2
return "Status(" + strconv.Itoa(int(s)) + ")"
}
return statusNames[s]
}
type Bytes int64
const (
_ = iota3
KB Bytes = 1 << (10 * iota)4
MB
GB
)- 1Zero is the value of an unset field. Keep it invalid on purpose.
- 2Nothing stops Status(9): a Go enum is only a named integer.
- 3Blank skips iota 0, so KB uses iota 1.
- 4MB and GB repeat this expression with the next iota.
My enum starts with an unknown value at zero, so a missing field reads as not set, not as a real state.
| code | meaning |
|---|---|
| const big = 1 << 100 | Untyped and exact. It must fit the type where you use it. |
| 5 / 2, 5 / 2.0 | 2, then 2.5. The operands set the kind of division. |
| 2 * time.Second | 2 takes type Duration, so this compiles. |
| n * time.Second | n * time.Second (mismatched types int and time.Duration) |
| time.Duration(n) * time.Second | The fix: an explicit conversion. |
| x := 1.5 | A variable needs a type, so it takes the default: float64. |
| uint8(300) | constant 300 overflows uint8 |
Default types: int, float64, rune, complex128, string, bool.
An untyped constant takes the type its use needs. A variable never changes type, so I convert it by hand.
| form | checked | on failure |
|---|---|---|
| T(x), numbers | Compile time | Keeps the low bits, with no error. Check the range first. |
| []byte(s), string(b) | Compile time | Cannot fail. Each one copies the bytes. |
| [4]int(s) | Run time | Panics if the slice is too short. |
| v, ok := x.(T) | Run time | ok is false, and v is the zero value. |
| v := x.(T) | Run time | Panics. |
| switch v := x.(type) | Run time | The default case runs. |
An assertion works only on an interface value, and it matches the exact dynamic type. See G4.
A conversion changes the type at compile time. An assertion reads the dynamic type at run time and can fail.
// IntField reads a number from JSON decoded into map[string]any.
// encoding/json stores every number as float64, so .(int) never matches.
func IntField(m map[string]any, key string) (int, error) {
switch v := m[key].(type) {1
case nil:2
return 0, fmt.Errorf("%s missing: %w", key, ErrField)
case float64:
if v != math.Trunc(v) {3
return 0, fmt.Errorf("%s is %v: %w", key, v, ErrField)
}
return int(v), nil
default:
return 0, fmt.Errorf("%s is %T: %w", key, v, ErrField)
}
}- 1One expression covers every case. In each case, v has that type.
- 2A missing key gives a nil interface, so this case catches it.
- 3A float converted to int cuts the fraction. Refuse it instead.
// ToInt32 checks first, because a conversion cuts the high bits and
// reports nothing.
func ToInt32(n int64) (int32, error) {
if n < math.MinInt32 || n > math.MaxInt32 {
return 0, fmt.Errorf("%d: %w", n, ErrRange)
}
return int32(n), nil1
}- 1Safe here, after the range check.
JSON numbers decode to float64 in an any, so an assertion to int always fails. I switch on the real type.
| type | == | map key |
|---|---|---|
| Numbers, strings, bools, pointers, chans | Yes | Yes |
| Struct or array of comparable parts | Yes | Yes |
| Slice, map, func | Compile error | Compile error |
| Interface | Panics on a slice inside | Panics on a slice inside |
| Struct with a float field | NaN never equals NaN | NaN key is unreachable |
| time.Time | Use t.Equal | Convert to Unix first |
true false
false
foundtime.Time == compares the location and the monotonic reading too, not only the instant.
// Key is comparable, so it works as a map key with no string building.
type Key struct {1
Tenant string
ID int
}
// Dedupe keeps the first of each value. T must support ==.
func Dedupe[T comparable]2(in []T) []T {
seen := make(map[T]struct{}, len(in))
out := in[:0:0]3
for _, v := range in {
if _, dup := seen[v]; dup {
continue
}
seen[v] = struct{}{}
out = append(out, v)
}
return out
}- 1A struct key needs no string building, and two fields cannot run together.
- 2Since Go 1.20 an interface also satisfies this, so T = any compiles and can panic on a slice.
- 3An empty slice with cap 0: the first append allocates, so Dedupe keeps its input intact. See G3.
Structs, arrays and pointers compare with ==. Slices, maps and funcs do not. An interface compiles, and it can panic at run time.
| [3]int | []int | |
|---|---|---|
| Length | Part of the type | Run time |
| Assignment | Copies every element | Copies 3 words, shares elements |
| == and map key | Yes | No |
| Can grow | No | Yes |
| Zero value | All elements zero | nil |
| Good for | [32]byte hash, fixed tables | Everything else |
sha256.Sum256 returns [32]byte, so a digest works directly as a map key.
An array is a value with its length in the type. I use one for fixed keys such as a hash, and a slice everywhere else.
// Patch tells "leave it alone" (nil) from "set to zero" (a pointer to 0).
type Patch struct {
Name *string `json:"name,omitempty"`
Age *int `json:"age,omitempty"`1
}
func (p Patch) Apply(to *Person) {
if p.Name != nil {
to.Name = *p.Name
}
if p.Age != nil {
to.Age = *p.Age
}
}
// Birthday builds a patch from a computed value in one expression.
func Birthday(u Person) Patch { return Patch{Age: new(u.Age + 1)2} }- 1nil: leave it alone. A pointer to 0: set it to 0. An int cannot say both.
- 2Go 1.26: new takes an expression. It allocates, stores the value and returns the pointer.
2 9 0 1
{"name":"a"}
{"name":"b","age":0}A pointer field separates absent from zero. new(expr) builds that pointer in one expression.
- a := 1
- b := a
- b = 2
- Pick a kind of value, then step through the assignment and the write.
- The slice row with append changes only b: the array had no spare room, so b moved. G3 shows the steps.
- A string has no write operation. += builds a new string, so the shared bytes stay safe.
Assignment copies the top level. A pointer, slice or map inside still points at the same data, so a deep copy is my job.
| since | what changed | what it means here |
|---|---|---|
| 1.20 | Slice to array conversion: [4]byte(x). unsafe.SliceData, String and StringData. Ordinary interfaces satisfy comparable. Struct compare stops at the first mismatch, by spec. | A generic map key can now be any, with a run-time panic as the price. |
| 1.21 | Built-ins min, max and clear. | clear zeroes a slice or empties a map. |
| 1.22 | Each loop iteration creates new variables. Range over an integer. | A pointer to a range variable now differs per iteration. |
| 1.23 | Range over functions. | Your own types can work with for range. |
| 1.24 | Generic type aliases. | A library can rename a generic type with no break. |
| 1.25 | No language change. The spec drops core types. | Read older posts on core types with care. |
| 1.26 | new takes an expression. A generic type can refer to itself in its type parameters. | Optional fields need no helper function. See panel P. |
| 1.27 | Generic methods. A struct literal key can be any valid field selector. Function type inference applies to all assignments to a matching function type. | Interface methods still cannot have type parameters, and a generic method cannot implement one. |
package main
import "fmt"
type Bag map[string]any
func (b Bag) As[T any]1(key string) (T, bool) {
v, ok := b[key].(T)
return v, ok
}
func main() {
b := Bag{"n": 7, "s": "hi"}
fmt.Println(b.As[int]("n"))
fmt.Println(b.As[string]("n"))
}- 1The method declares its own type parameter.
7 true
falsepackage main
import "fmt"
type Base struct{ ID int }
type User struct {
Base
Name string
}
func main() {
u := User{ID: 71, Name: "a"}
fmt.Println(u.ID, u.Base, u)
}- 1ID belongs to the embedded Base. Older Go needs User{Base: Base{ID: 7}}.
7 {7} {{7} a}| when | the moment | what to do or say |
|---|---|---|
| build | The store holds records in a map. | Use map[string]Item and return Item by value. The copy leaves the lock safely. |
| build | Item gets a slice field. | Clone it before you return, because a struct copy shares the slice. |
| build | A struct has a mutex. | Use pointer receivers on every method, and pass &store. |
| build | A PATCH body has optional fields. | Use pointer fields, so 0 and absent stay different. |
| build | A record has a state. | Use a named int with iota, a String method, and an unknown value at zero. |
| talk | "Value or pointer here?" | Say what must be shared, then the size. Quote the numbers in panel U. |
| talk | "Why does this not satisfy the interface?" | The method has a pointer receiver, so only *T has it in its method set. |
| talk | "Is a pointer faster?" | Not by default. It can move the value to the heap: 19.2 ns against 6.7 ns. |
I return values from the store, so no caller can change data outside the lock.
0 of 12 known
Predict the output.
package main import "fmt" func main() { var m map[string]int v, ok := m["a"] fmt.Println(v, ok, len(m)) delete(m, "a") for range m { fmt.Println("never") } fmt.Println("reads are safe") m["a"] = 1 fmt.Println("after the write") }Predict the output.
package main import "fmt" type Item struct{ Qty int } func main() { items := []Item{{1}, {2}} for _, it := range items { it.Qty *= 10 } fmt.Println(items) for i := range items { items[i].Qty *= 10 } fmt.Println(items) }Predict the output.
package main import "fmt" func bump(a [3]int) { a[2] = 100 } func main() { a := [3]int{1, 2, 3} b := a b[0] = 9 s := a[:] s[1] = 7 bump(a) fmt.Println(a, b, s) }Predict the output.
package main import "fmt" type Doc struct { Title string Tags []string Meta map[string]int } func main() { a := Doc{"a", []string{"x"}, map[string]int{"v": 1}} b := a b.Title = "b" b.Tags[0] = "y" b.Meta["v"] = 2 b.Tags = append(b.Tags, "z") fmt.Println(a) fmt.Println(b) }Predict the output.
package main import "fmt" type V struct{ n int } func (v V) Val() int { return v.n } func (v *V) Ptr() int { return v.n } func main() { v := V{1} f, g := v.Val, v.Ptr v.n = 2 fmt.Println(f(), g()) }Predict the output.
package main import "fmt" type Base struct{} func (Base) Name() string { return "base" } func (b Base) Hello() string { return "hello from " + b.Name() } type Child struct{ Base } func (Child) Name() string { return "child" } func main() { c := Child{} fmt.Println(c.Name()) fmt.Println(c.Hello()) fmt.Println(c.Base.Name()) }Predict the output.
package main import "fmt" const ( A = iota * 10 B _ C D = "x" E F = iota ) const G = iota func main() { fmt.Println(A, B, C, D, E, F, G) }Predict the output.
package main import "fmt" const big = 1 << 100 func main() { fmt.Println(big >> 98) fmt.Println(5/2, 5/2.0) fmt.Println(0.1+0.2 == 0.3) a, b := 0.1, 0.2 fmt.Println(a+b == 0.3) }Predict the output.
package main import "fmt" func main() { n, big := 300, 1<<40 f := -1.9 fmt.Println(uint8(n), int8(n)) fmt.Println(int32(big), int(f)) fmt.Println(string(rune(0x4E16)), []byte("é")) }Predict the output.
package main import "fmt" type ID int func main() { var v any = ID(7) _, isInt := v.(int) id, isID := v.(ID) fmt.Println(isInt, id, isID, int(id)+1) defer func() { fmt.Println("recovered:", recover()) }() fmt.Println(v.(string)) }Predict the output.
package main import "fmt" func main() { var a, b any = 1, 1 fmt.Println(a == b) a, b = []int{1}, 1 fmt.Println(a == b) a, b = []int{1}, []int{1} defer func() { fmt.Println("recovered:", recover()) }() fmt.Println(a == b) }Predict the output.
package main import "fmt" func main() { s := []int{1, 2, 3} a := [2]int(s) p := (*[2]int)(s) s[0] = 9 fmt.Println(a, *p) defer func() { fmt.Println("recovered:", recover()) }() fmt.Println([4]int(s)) }
- 8 B
- 1.2 ns by value; 1.3 ns by pointer.
- 64 B
- 1.8 ns by value; 1.3 ns by pointer.
- 1 KB
- 15.5 ns by value; 1.2 ns by pointer.
- return
- 6.7 ns by value; 19.2 ns and 1 allocation by pointer.
- words
- Slice 24 B; string and interface 16 B; map and pointer 8 B; struct{} 0 B.
Go 1.27.3, 8-core Intel i9 laptop, GOMAXPROCS 16, median of 3 runs of 1 s, on a busy machine. Each call stays out of line. Use these as orders of magnitude.