Usage analysis of GO language mapping (Map)
- 2020-05-07 19:53:11
- OfStack
This article illustrates the use of GO language mappings (Map). Share with you for your reference. The details are as follows:
A map is a built-in data structure that holds an unordered collection of key-value pairs.
(1) map creation
make ( map [KeyType] ValueType, initialCapacity )
make ( map [KeyType] ValueType )
map [KeyType ] ValueType {}
map [KeyType ] ValueType { key1 : value1, key2: value2, ... , keyN : valueN}
The difference between the first and the second is that the initial capacity is not specified. However, it is not necessary to worry about this when using map, because the essence of map is that if the capacity of 1 denser is not enough, it will automatically expand:
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]
Padding and traversal of (2) maps
func test2() {
map1 := make(map[string]string)
map1["a"] = "1"
map1["b"] = "2"
map1["c"] = "3"
for key, value := range map1 {
fmt.Printf("%s->%-10s", key, value)
}
}
As shown above, the array is populated by map[key] = value, with each item returning two values, keys, and values as you traverse the map. The results are as follows:
a- > 1 b- > 2 c- > 3
Find, modify, and delete the (3) map
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" // Modifying a map is no different than adding a map, right
fmt.Printf("%v\n", map4)
fmt.Println(" delete b : ")
delete(map4, "b")
fmt.Printf("%v", map4)
}
When map specifies that key takes the corresponding value, it can be specified to return two values, the first is the corresponding value, the second is 1 bool, indicating whether there is a value. As above, "a" must have a value, and "b" must have no value.
Modifying a map is no different than adding a map; if the specified key does not exist, it is created; otherwise, it is modified.
Delete is delete, the built-in function of go, and the output is as follows:
true,1
false,
map[a:8 b:2 c:3]
Delete b:
map[a:8 c:3]
I hope that this article has been helpful to your GO programming language.