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!

3 Comments

Leave a 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>