Immutability
suggest changeAn immutable value can't change after it's created. Immutable data is easier to reason about: you can pass it to any function, store it, return it and share it between goroutines without worrying that someone will modify it behind your back.
Go has no final, readonly or const qualifier for variables, fields or parameters. Only constants are truly immutable, and only a few kinds of values can be constants. Everything else is immutable by design rather than enforced by the compiler.
This article shows what Go makes immutable for you, where mutation leaks through shared memory, and the patterns for building immutable types: unexported fields, defensive copies, value receivers, With methods, read-only iterators, full slice expressions and copy-on-write with atomic.Pointer.
Constants
A const can't be reassigned, but constants are limited to booleans, numbers, runes and strings:
package main
import "fmt"
const MaxRetries = 3
// const Primes = []int{2, 3, 5, 7} // compile error: []int{…} (value of type []int) is not constant
// a package-level variable is not protected: any code in the package can change it
var Primes = []int{2, 3, 5, 7}
// a function returns a fresh slice on every call
func PrimesSlice() []int { return []int{2, 3, 5, 7} }
// an array is a value, so every caller gets its own copy
var primes = [...]int{2, 3, 5, 7}
func PrimesArray() [4]int { return primes }
func main() {
// MaxRetries = 5 // compile error: cannot assign to MaxRetries
p := Primes
p[0] = 0 // modifies the shared global
fmt.Println(Primes)
s := PrimesSlice()
s[0] = 0
fmt.Println(PrimesSlice())
a := PrimesArray()
a[0] = 0
fmt.Println(PrimesArray(), a)
}
[0 3 5 7]
[2 3 5 7]
[2 3 5 7] [0 3 5 7]
There are no constant slices, maps or structs. An exported package-level var is a mutable global: any importer can write pkg.Primes[0] = 0 and break every other user of the package. When a table of values must stay fixed, keep the variable unexported and expose it through a function that returns a copy.
Strings are immutable
Strings are the one built-in reference-like type that can't be modified:
package main
import "fmt"
func main() {
s := "hello"
// s[0] = 'H' // compile error: cannot assign to s[0] (neither addressable nor a map index expression)
t := s // copies the string header, shares the bytes
s += ", world" // creates a new string; t is unaffected
fmt.Println(s)
fmt.Println(t)
b := []byte(t) // conversion copies the bytes
b[0] = 'H'
fmt.Println(string(b), t)
}
hello, world
hello
Hello hello
A string is a pointer to bytes plus a length. Assigning or passing a string copies only those two words, which is cheap and safe because nobody can change the bytes. += doesn't modify the string, it builds a new one.
The price is that converting between string and []byte copies the data (the compiler optimizes some cases, like m[string(b)] lookups). When you build a string piece by piece, use strings.Builder instead of repeated +=. See Strings for more.
Values vs. shared memory
Whether an assignment shares data depends on the type:
package main
import "fmt"
type Point struct{ X, Y int }
func main() {
// arrays and structs are values: assignment copies them
a := [3]int{1, 2, 3}
a2 := a
a2[0] = 100
p := Point{1, 2}
p2 := p
p2.X = 100
fmt.Println(a, a2)
fmt.Println(p, p2)
// slices and maps are small headers that point to shared data
s := []int{1, 2, 3}
s2 := s
s2[0] = 100
m := map[string]int{"a": 1}
m2 := m
m2["a"] = 100
fmt.Println(s, s2)
fmt.Println(m, m2)
}
[1 2 3] [100 2 3]
{1 2} {100 2}
[100 2 3] [100 2 3]
map[a:100] map[a:100]
Booleans, numbers, strings, arrays and structs made only of those are copied on assignment, on function calls and when returned. If you have a copy, nobody else can change it. Such types are effectively immutable from the receiver's point of view.
Slices, maps, pointers, channels and functions share the underlying data. So does any struct that contains them. Copying such a struct is a shallow copy:
package main
import "fmt"
type Config struct {
Name string
Tags []string
Limit map[string]int
}
func main() {
orig := Config{
Name: "prod",
Tags: []string{"a", "b"},
Limit: map[string]int{"rps": 100},
}
cp := orig // shallow copy
cp.Name = "test" // independent
cp.Tags[0] = "changed" // shared!
cp.Limit["rps"] = 1 // shared!
fmt.Printf("%+v\n", orig)
fmt.Printf("%+v\n", cp)
}
{Name:prod Tags:[changed b] Limit:map[rps:1]}
{Name:test Tags:[changed b] Limit:map[rps:1]}
Most immutability bugs in Go come from this: a slice or a map that two parts of the program think they own. The rest of this article is about controlling who can reach that shared memory. Duplicate a struct covers copying in more detail.
Immutable types: unexported fields and no setters
The compiler can't stop code from assigning to a field, but it can stop code outside the package from seeing the field. A type with unexported fields, a constructor and only getter methods is immutable to its users.
The constructor and the getters must also copy slices and maps, otherwise the caller keeps a back door into the internal state:
// file user/user.go
package user
import (
"errors"
"slices"
"strings"
)
// User is immutable: fields are unexported and there are no setters.
type User struct {
name string
roles []string
}
func New(name string, roles ...string) (User, error) {
if strings.TrimSpace(name) == "" {
return User{}, errors.New("user: empty name")
}
// copy: the caller may still hold and modify the slice it passed
return User{name: name, roles: slices.Clone(roles)}, nil
}
func (u User) Name() string { return u.name }
// RolesLeaky returns the internal slice: callers can modify it.
func (u User) RolesLeaky() []string { return u.roles }
// Roles returns a copy.
func (u User) Roles() []string { return slices.Clone(u.roles) }
func (u User) HasRole(role string) bool { return slices.Contains(u.roles, role) }
// file main.go
package main
import (
"fmt"
"example.com/app/user"
)
func main() {
roles := []string{"reader"}
u, err := user.New("alice", roles...)
if err != nil {
panic(err)
}
// u.name = "bob" // compile error: u.name undefined
roles[0] = "admin" // doesn't affect u: New made a copy
fmt.Println(u.Name(), u.Roles(), u.HasRole("admin"))
r := u.Roles()
r[0] = "admin" // modifies only the copy
fmt.Println(u.Roles(), u.HasRole("admin"))
leak := u.RolesLeaky()
leak[0] = "admin" // modifies u's internal state!
fmt.Println(u.Roles(), u.HasRole("admin"))
}
alice [reader] false
[reader] false
[admin] true
A few details matter:
roles ...stringis a slice. A caller can pass an existing slice withroles..., and then the function receives that very slice, not a copy. That's whyNewclones it.slices.Cloneandmaps.Clonemake shallow copies. If elements are pointers, slices or maps, copy them too (see Deep copies below).- Validation in the constructor plus no setters means every
Userthat exists is valid. Code that receives aUsernever needs to re-check it. - Returning
Userby value instead of*Usersignals immutability: there's no pointer through which anyone could change it. Unexported fields still keep the zero valueUser{}constructible from outside, so decide what it means (here: a user with an empty name) or check for it.
Inside the package the fields remain writable. Immutability is a property of the package's API, so keep the package small enough that you can see every write.
Value receivers and methods that return new values
Methods on an immutable type never modify the receiver. They return a new value instead. Use value receivers: the method works on a copy, so even an accidental write can't affect the caller.
package main
import (
"fmt"
"time"
)
// Money is an immutable value type: methods have value receivers
// and return new values instead of modifying the receiver.
type Money struct {
cents int64
currency string
}
func NewMoney(cents int64, currency string) Money {
return Money{cents: cents, currency: currency}
}
func (m Money) Add(o Money) Money {
if m.currency != o.currency {
panic("currency mismatch")
}
return Money{cents: m.cents + o.cents, currency: m.currency}
}
func (m Money) Mul(n int64) Money {
m.cents *= n // m is a copy, the caller's value is unchanged
return m
}
func (m Money) String() string {
return fmt.Sprintf("%d.%02d %s", m.cents/100, m.cents%100, m.currency)
}
func main() {
price := NewMoney(1999, "USD")
total := price.Mul(3).Add(NewMoney(500, "USD"))
fmt.Println(price, total)
// time.Time works the same way
t := time.Date(2026, 10, 17, 12, 0, 0, 0, time.UTC)
later := t.Add(36 * time.Hour)
fmt.Println(t.Format(time.DateTime))
fmt.Println(later.Format(time.DateTime))
}
19.99 USD 64.97 USD
2026-10-17 12:00:00
2026-10-19 00:00:00
This is how the standard library's value types work: time.Time, time.Duration, netip.Addr and netip.Prefix have only value methods that return new values. (big.Int is the opposite: it's deliberately mutable to avoid allocations.) Immutable values are also comparable with == and safe as map keys as long as all fields are comparable.
Copying is cheap for small structs. For large ones, a pointer receiver avoids the copy, but then you must be disciplined: the method must not write through the pointer. See Pointer vs. value methods.
With methods: modified copies
To "change" one field of an immutable value, return a copy with that field replaced. When the field is a map or a slice, copy it before modifying, or the original sees the change too:
package main
import (
"fmt"
"maps"
"slices"
)
type Request struct {
Method string
URL string
Headers map[string]string
}
// WithHeader returns a copy of r with the header set; r is not modified.
func (r Request) WithHeader(key, value string) Request {
h := maps.Clone(r.Headers) // maps.Clone(nil) returns nil
if h == nil {
h = make(map[string]string)
}
h[key] = value
r.Headers = h
return r
}
func main() {
base := Request{Method: "GET", URL: "/api"}
jsonReq := base.WithHeader("Accept", "application/json")
authed := jsonReq.WithHeader("Authorization", "Bearer xyz")
fmt.Println(len(base.Headers), len(jsonReq.Headers), len(authed.Headers))
fmt.Println(slices.Sorted(maps.Keys(authed.Headers)))
}
0 1 2
[Accept Authorization]
base, jsonReq and authed are independent, so you can keep a base request as a template and derive variants from it. context.WithValue, context.WithTimeout and http.Request.WithContext follow the same idea: they return a new value and leave the parent alone. See Context is a tree of values.
Copying the whole map for each change costs O(n). That's fine for a handful of headers. For large collections with frequent updates, use a mutable type guarded by a mutex, or a persistent data structure library.
Read-only views with iterators
Returning a copy of a big slice from a getter allocates on every call. When callers only need to read, give them an iterator instead of a slice. An iter.Seq lets them range over the elements but never exposes the slice itself:
package main
import (
"fmt"
"iter"
"slices"
)
type Playlist struct {
songs []string
}
func (p *Playlist) Add(song string) { p.songs = append(p.songs, song) }
// Len and At give indexed read-only access.
func (p *Playlist) Len() int { return len(p.songs) }
func (p *Playlist) At(i int) string { return p.songs[i] }
// Songs returns an iterator: callers can read the songs
// but never get the underlying slice.
func (p *Playlist) Songs() iter.Seq[string] {
return slices.Values(p.songs)
}
func main() {
var p Playlist
p.Add("Intro")
p.Add("Outro")
for s := range p.Songs() {
fmt.Println(s)
}
// a caller that needs a slice collects its own copy
mine := slices.Collect(p.Songs())
mine[0] = "changed"
fmt.Println(mine, p.At(0), p.Len())
}
Intro
Outro
[changed Outro] Intro 2
Len and At are the classic alternative, used for example by reflect.Value and go/types. Both approaches hand out elements, not the slice. If the elements themselves are pointers, the caller can still modify what they point to; return values or copies for those.
Full slice expressions prevent append surprises
A sub-slice shares the backing array with the original. If the sub-slice has spare capacity, append writes into the original's elements:
package main
import "fmt"
func main() {
all := make([]int, 0, 10)
all = append(all, 1, 2, 3, 4)
first := all[:2] // len 2, cap 10: shares spare capacity with all
first = append(first, 99)
fmt.Println(all, first) // all[2] was overwritten!
all = make([]int, 0, 10)
all = append(all, 1, 2, 3, 4)
safe := all[:2:2] // full slice expression: len 2, cap 2
safe = append(safe, 99) // exceeds cap: append copies to a new array
fmt.Println(all, safe)
}
[1 2 99 4] [1 2 99]
[1 2 3 4] [1 2 99]
s[low:high:max] sets the capacity to max-low. With capacity equal to length, the first append must allocate, so the original is never overwritten. Use it when you hand out a window into a slice you keep using. It doesn't stop the receiver from writing safe[0] = 5, which still changes all, so it protects only against appends. For full protection, copy.
Deep copies
slices.Clone and maps.Clone copy one level. When elements contain pointers, slices or maps, a clone still shares them:
package main
import (
"fmt"
"maps"
"slices"
)
type Team struct {
Name string
Members []string
}
type Org struct {
Teams map[string]*Team
}
// Clone returns a deep copy: no memory is shared with o.
func (o Org) Clone() Org {
teams := make(map[string]*Team, len(o.Teams))
for k, t := range o.Teams {
teams[k] = &Team{Name: t.Name, Members: slices.Clone(t.Members)}
}
return Org{Teams: teams}
}
func main() {
org := Org{Teams: map[string]*Team{
"eng": {Name: "Engineering", Members: []string{"ann", "bob"}},
}}
shallow := Org{Teams: maps.Clone(org.Teams)}
shallow.Teams["eng"].Members[0] = "zed" // *Team is shared
fmt.Println(org.Teams["eng"].Members)
deep := org.Clone()
deep.Teams["eng"].Members[0] = "amy"
deep.Teams["eng"].Name = "Eng"
fmt.Println(org.Teams["eng"].Name, org.Teams["eng"].Members)
fmt.Println(deep.Teams["eng"].Name, deep.Teams["eng"].Members)
}
[zed bob]
Engineering [zed bob]
Eng [amy bob]
Go has no generic deep copy. Write a Clone method by hand: it's explicit, fast and type-checked, and when you add a field the method is the obvious place to update. Reflection-based deep copy libraries and round-tripping through JSON or gob work, but they're slow and silently skip unexported fields.
A design that avoids pointers in the first place (map[string]Team instead of map[string]*Team, arrays instead of slices for fixed sizes) needs less copying.
Immutability and concurrency
Data that nobody writes can be read by any number of goroutines without locks. A common pattern is copy-on-write: readers load a pointer to an immutable snapshot, and writers build a new snapshot and swap the pointer atomically:
package main
import (
"fmt"
"maps"
"sync"
"sync/atomic"
)
// Config is never modified after it's published.
type Config struct {
Version int
Features map[string]bool
}
var current atomic.Pointer[Config]
func Load() *Config { return current.Load() }
// Update builds a new Config from the old one and publishes it atomically.
func Update(feature string, on bool) {
for {
old := current.Load()
next := &Config{
Version: old.Version + 1,
Features: maps.Clone(old.Features),
}
next.Features[feature] = on
if current.CompareAndSwap(old, next) {
return
}
// another goroutine published first: retry with its version
}
}
func main() {
current.Store(&Config{Version: 1, Features: map[string]bool{}})
var wg sync.WaitGroup
for i := range 10 {
wg.Go(func() {
Update(fmt.Sprintf("f%d", i), true)
})
wg.Go(func() {
cfg := Load() // no lock: cfg is never mutated
_ = len(cfg.Features)
})
}
wg.Wait()
cfg := Load()
fmt.Println(cfg.Version, len(cfg.Features))
}
11 10
Readers never block and always see a consistent snapshot: a reader that loaded version 5 keeps using version 5 even while writers publish 6 and 7. The CompareAndSwap loop makes concurrent updates safe without a mutex: if two writers race, one retries on top of the other's result, so no update is lost.
This works only if the rule "never modify a published Config" holds. Nothing enforces it, so keep the fields unexported or document the rule loudly. Copy-on-write suits data that is read often and written rarely, like configuration, routing tables or feature flags. For write-heavy data, a mutex is simpler and cheaper.
The race detector catches violations: a write to a map that another goroutine reads is reported as a data race.
Summary
| goal | technique |
|---|---|
| fixed number or string | const |
| fixed table of values | unexported var plus a function returning a copy, or an array |
| immutable type | unexported fields, constructor that validates, getters only |
| don't share caller's data | slices.Clone / maps.Clone arguments in the constructor |
| don't share internal data | return copies, or an iter.Seq / Len + At |
| "modify" an immutable value | value receiver returning a new value; WithX methods |
| hand out a window into a slice | full slice expression s[a:b:b] |
| nested data | hand-written Clone method |
| share between goroutines | immutable snapshots behind atomic.Pointer |
- Go enforces immutability only for constants and strings; everything else is a matter of API design
- values (numbers, strings, arrays, structs of those) are copied on assignment; slices, maps and pointers share memory
- copying a struct with slice or map fields is shallow
- copy slices and maps on the way in and on the way out of an immutable type
- immutable data can be shared across goroutines without locks