package main import ( "fmt" "maps" ) func main() { // A map maps keys to values. The zero value of a map is nil. A nil map has no keys, nor can keys be added. var m map[string]int // To create a map, use the builtin make function. The make function allocates and // initializes a hash map data structure and returns a map value that points to it. m = make(map[string]int) // Set key/value pairs using typical name[key] = val syntax. m["k1"] = 7 m["k2"] = 13 fmt.Println("map:", m) // Get a value for a key with name[key]. v1 := m["k1"] fmt.Println("v1:", v1) // If the key is not present in the map, the result is the zero value for the map's value type. v3 := m["k3"] fmt.Println("v3:", v3) fmt.Println("len:", len(m)) // The builtin delete removes key/value pairs from a map. delete(m, "k2") delete(m, "k2") // Deleting a non-existent key does not cause an error. fmt.Println("map:", m) // The builtin "maps" package provides a function Clear to remove all key/value pairs from a map. clear(m) fmt.Println("map:", m) // The optional second return value when getting a value from a map indicates if the key was present in the map. _, prs := m["k2"] fmt.Println("prs:", prs) // Map literals are like struct literals, but the keys are required. n := map[string]int{"foo": 1, "bar": 2} fmt.Println("map:", n) // The builtin "maps" package provides a function Equal to compare two maps for equality. n2 := map[string]int{"foo": 1, "bar": 2} if maps.Equal(n, n2) { fmt.Println("n == n2") } }