Original post

More about maps: looking up keys, adding and updating values, and how to update the fields of a struct within a map. This mini-tutorial is part of a series on everything you need to know about maps in !

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

Once we have declared and initialized a map of the required type, what can we do with it?

Looking up keys in a Go map

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

Assigning to struct fields in maps

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

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