Junior
What are the features of the syntax for getting and setting values in a map in Go language?
sobes.tech AI
Answer from AI
When retrieving a value by key from a map, it returns two values: the value itself and a boolean indicating whether the key exists.
m := map[string]int{"a": 1}
v, ok := m["a"] // v = 1, ok = true
v, ok = m["b"] // v = 0 (zero value for int), ok = false
To assign or update a value, the = operator is used.
m["c"] = 3 // Adding a new key
m["a"] = 10 // Updating an existing value
Removing an element from a map is done using the built-in delete function.
delete(m, "a") // Removing the key "a"
delete(m, "b") // Attempting to delete a non-existent key does not cause an error