go compile_error ai_generated true

cannot assign to struct field in map

ID: go/cannot-assign-to-struct-field

Also available as: JSON · Markdown
92%Fix Rate
92%Confidence
50Evidence
2023-01-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1 active

Root Cause

Can't modify a struct field directly in a map. Go maps return copies, not references.

generic

Workarounds

  1. 95% success Use a map of pointers: map[string]*MyStruct
    m := map[string]*MyStruct{"key": &MyStruct{Field: 1}}
    m["key"].Field = 2  // works!

    Sources: https://go.dev/blog/maps

  2. 90% success Copy, modify, reassign: tmp := m[k]; tmp.Field = val; m[k] = tmp
    tmp := m[k]; tmp.Field = val; m[k] = tmp

    Sources: https://go.dev/ref/spec#Assignments

Dead Ends

Common approaches that don't work:

  1. Use unsafe to get a pointer to the map value 95% fail

    Unsafe and undefined behavior — map values can move in memory

  2. Use a different data structure 55% fail

    Maps are fine — just use pointer values

Error Chain

Preceded by: