A Tour of Go Mutating Maps

时间:2023-03-10 04:06:54
A Tour of Go  Mutating Maps

Insert or update an element in map m:

m[key] = elem

Retrieve an element:

elem = m[key]

Delete an element:

delete(m, key)

Test that a key is present with a two-value assignment:

elem, ok = m[key]

If key is in mok is true. If not, ok is false and elem is the zero value for the map's element type.

Similarly, when reading from a map if the key is not present the result is the zero value for the map's element type.

package main
import "fmt" func main() {
m := make(map[string]int) m["Answer"] =
fmt.Println("The value:", m["Answer"]) m["Answer"] =
fmt.Println("The value:", m["Answer"]) v, ok := m["Answer"]
fmt.Println("The value:", v, "Present?", ok) delete(m, "Answer")
fmt.Println("The value:", m["Answer"]) v2, ok2 := m["Answer"]
fmt.Println("The value:", v2, "Present?", ok2)
}

好变态的map用法,真不知道google是怎怎么想的