Cannot Assign to Struct Field in Map

cannot assign to struct field m["key"].Name in map

Quick Answer

Map values in Go are not addressable. You must copy the struct, modify it, and write it back to the map.

Why This Happens

When a map holds struct values, you cannot directly modify a field of the struct stored in the map. This is because map elements are not addressable in Go, so the compiler cannot give you a pointer to modify in place. You must read the value, modify the copy, and store it back.

The Problem

type User struct {
    Name string
    Age  int
}

func main() {
    users := map[string]User{
        "alice": {Name: "Alice", Age: 30},
    }
    users["alice"].Age = 31 // cannot assign to struct field
}

The Fix

func main() {
    users := map[string]User{
        "alice": {Name: "Alice", Age: 30},
    }
    u := users["alice"]
    u.Age = 31
    users["alice"] = u
}

Step-by-Step Fix

  1. 1

    Identify the direct field assignment

    Find the line where you are trying to modify a struct field directly through a map access.

  2. 2

    Copy the struct value

    Read the struct from the map into a local variable.

  3. 3

    Modify and write back

    Modify the local copy and assign it back to the map. Alternatively, use a map of pointers: map[string]*User.

Bugsly catches this automatically

Bugsly's AI analyzes this error pattern in real-time, explains what went wrong in plain English, and suggests the exact fix — before your users even report it.

Try Bugsly free