Update Value for Key in Map

To update value for a key in Map in Go language, assign the new value to map[key] using assignment operator.

If the key we are updating is already present, then the corresponding value is updated with the new value.

If the key we are updating is not already present, then a new key:value pair with the given key and value would be added to the map.

Syntax

The syntax to update key of Map x is

</>
Copy
x[key] = new_value

Examples

Update Key with New Value

In the following program, we take a map from string to string, with some initial values. We then update value for key "a".

example.go

</>
Copy
package main

import "fmt"

func main() {
	map1 := map[string]string{
		"a": "apple",
		"b": "banana",
	}

	map1["a"] = "avocado"

	fmt.Print(map1)
}

Output

map[a:avocado b:banana]

Update key in Map, key not present already

In the following program, we take a map, and update the value for key "c". But key "c" is not present already in the map. In such case a new key:value pair is added to the map.

example.go

</>
Copy
package main

import "fmt"

func main() {
	map1 := map[string]string{
		"a": "apple",
		"b": "banana",
	}

	map1["c"] = "cherry"

	fmt.Print(map1)
}

Output

map[a:apple b:banana c:cherry]

Conclusion

In this Golang Tutorial, we learned how to update value for a key in Map, with the help of example programs.