Previous blog Introduction to the Go language arrays and slices--go language Summary (3)--arrays and slices, this blog introduction to the Go Language mapping (map)
A map is a built-in data structure used to hold unordered collections of key-value pairs.
(1) Creation of mappings
Make (map [KeyType] ValueType, initialcapacity)
Make (map [KeyType] ValueType)
Map [KeyType] ValueType {}
Map [KeyType] ValueType {key1:value1, key2:value2, ..., Keyn:valuen}
As below, the array is created in 4 ways, where the first and second differences are that there is no initial capacity specified, but it is not necessary to care when using it, because the nature of the map determines that, once the capacity is insufficient, it automatically expands:
func test1 () {map1:= Make (map[string]string,5) MAP2:= Make (map[string]string) MAP3:= map[string]string{} MAP4:= map[string]string{"a":"1","b":"2","C":"3"} fmt. Println (Map1, MAP2, MAP3, MAP4)}
The output is as follows:
Map[] map[] map[] Map[c:3 A:1 B:2]
(2) Mapping of padding and traversal
func test2 () {map1:= Make (map[string]string) map1["a"] ="1"map1["b"] ="2"map1["C"] ="3" forKey, Value: =range Map1 {fmt. Printf ("%s->%-10s", key, Value)}}
As above, the array is populated using the map[key] = value method, and each entry returns 2 values, keys and values when traversing the map. The results are as follows:
a->1 b->2 c->3
(3) Lookup, modification, and deletion of mappings
func test3 () {MAP4:= map[string]string{"a":"1","b":"2","C":"3"} val, exist:= map4["a"] Val2, Exist2:= map4["D"] FMT. Printf ("%v,%v\n", exist, Val) fmt. Printf ("%v,%v\n", Exist2, val2) map4["a"] ="8" //There's no difference between modifying a map and adding a mapFmt. Printf ("%v\n", MAP4) fmt. Println ("Remove B:") Delete (MAP4,"b") fmt. Printf ("%v", MAP4)}
When the map specifies that the key takes the corresponding value, you can specify that two values be returned, the first is the corresponding value, and the second is a bool that indicates whether there is a value. As above, "a" must have a value, "B" is definitely not worth it.
There is no difference between modifying a map and adding a map, and if the specified key does not exist, create it, or modify it.
Delete is the built-in function delete using go, the output is as follows:
true,1false, Map[a:8 B:2 C:3] Delete b:map[a: 8 C:3]
Go Language Summary (4)--Mapping (map)