Cannot assign to struct field in map

Understanding Maps in Go

Have you ever come across an error “Cannot assign to struct field in map”? So what is the issue here?

Imagine that we have a structure:

package main

type Product struct {
	Name  string
	Image string
	Cdn   string
	Price float64
}

func main() {

	products := make(map[int]Product)

	products[0] = Product{"Blue Diamond Book", "https://localhost/split/bdb.png", "https://localhostcdn/split/bdb.png", 120.00}
	// Problem
	products[0].Price = 121.00

}

The Error

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

products[0].Price = 121.00

We’ll get an error: “Cannot assign to struct field in map”

Pointer Map Problem in Golang

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:

thisProduct, ok := products[0]

thisProduct” will get the Product 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.

// Solution
	if thisProduct, ok := products[0]; ok {
		thisProduct.Price = 121.00
		products[0] = thisProduct
	}

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

Tell your network!

5 Comments

  1. Thanks, Varun! Nice post. I recently came across the same ‘cannot assign to struct field in map issue’ while writing a series of tutorials on Go maps:

    Storing and retrieving map values

    Although I think the ‘read a variable out of the map, update it, and write it back to the map’ approach is the most flexible, another idea I’ve seen is to make your map a map of pointers to structs. Then you can update the map value directly.

    1. Thanks for the alternative. Though most people like me will feel more comfortable in above approach which doesn’t include pointer

Leave a Reply to S. Mandy

Click here to cancel reply.

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>