Storing and retrieving map values

Storing and retrieving map values

heart-balloon.png

Just give me all the bacon and eggs you have

Go maps are a great way to store and retrieve data by key, so how do we do that? Suppose we have some map containing data about breakfast foods, like this:

menu := map[string]float64{
    "eggs": 1.75,
    "bacon": 3.22,
    "hash browns": 1.89,
}

We can look up any key in the map using this syntax:

price := menu["hash browns"]

Adding and updating values in maps

We can also add new values (or change existing ones) using the same square bracket syntax:

menu["hash browns"] = 0.99

The cannot assign to struct field in map error

There's one little gotcha to look out for here: we can't assign to a struct field within a map. For example, suppose we had a type menuItem like this:

type menuItem struct{
    price float64
}

and a map of strings to menuItem:

var menu = map[string]menuItem{
    "beans": menuItem{
        price: 0.49,
    },
}

The diner manager tells us "There's a special price on beans today: 0.25." Can we update the price of beans directly using the standard map syntax?

menu["beans"].price = 0.25 // not allowed

Alas no:

./prog.go:16:22: cannot assign to struct field menu["beans"].price in map

However, there's an easy way around this: just read the value of menu["beans"], update it, and write it back to the map:

beans := menu["beans"]
beans.price = 0.25
menu["beans"] = beans

Next

This is part 3 of a Golang tutorial series on maps. Check out the other posts in the series:

Now that you know how to store and retrieve values in a map, what happens if you try to retrieve a value that isn't in the map? How can you find out if it exists or not? Find out in our next thrilling episode on Finding whether a map key exists!

Looking for help with Go?

If you found this article useful, and you'd like to learn more about Go, then I can help! I offer one-to-one or group training in Go development, for complete beginners through to experienced Gophers. Check out my Learn Golang with mentoring page to find out more, or email go@bitfieldconsulting.com. Looking forward to hearing from you!

Gopher image by egonelbre

Finding whether a Go map key exists

Finding whether a Go map key exists

Map types in Golang

Map types in Golang

0