Cannot assign to struct field in map

Understanding Maps in Go

Had you ever came across “Cannot assign to struct field in map”?
Let’s talk about this issue.

We have a data structure:

type Student struct{
Name String
Class String
Marks float64
}
var student map[int]Student
student=make(map[123]Student{Name:"XYZ",Class:"9th",Marks:72.4})

The Error

If we have to reassign value to a variable like this:

student[123].Marks=79

We’ll get a panic: “Cannot assign to struct field in map”

The reason for this panic is, the map is a pointer to value and Go checks the key, is it there or not. If you had used a map, you must have seen:

value, ok:= student[123]

value” will get the Student structure’s object and “ok” will get a bool value, that this key exists or not

So we have to assign the pointer to a variable.

value:=student[123]

Now, we can access and reassign the value of the Student structure’s object:
value.Marks=79
After making the required adjustments, this value can be assigned back to the same pointer.

Cannot assign to struct field in map

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top