Quidest?

Updating struct elements inside a map in Go

· Lorenzo Drumond

Go doesn’t allow you to modify fields of map elements directly like this:

1catalog[1].Title = "For the Love of Go"
2// This doesn't work
3
4// compiler error:
5// cannot assign to struct field catalog[1].Title in map

We have to get the element out of the map, assign it to some variable, and modify the variable instead. We can then use the modified value to overwrite the original book:

1b := catalog[1]
2b.Title = "For the Love of Go"
3catalog[1] = b

References

Next -> non-existent-keys-in-go-maps

#programming #golang #struct #for_the_love_of_go #map #element