The examples in this article describe the use of Go Language mapping (map). Share to everyone for your reference. Specific as follows:
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:
Copy the Code code as follows:
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
Copy the Code code as follows:
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 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
Copy the Code code as follows:
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"//Modify mappings and add mappings no difference
Fmt. Printf ("%v\n", MAP4)
Fmt. Println ("Delete 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,1
False
Map[a:8 B:2 C:3]
Remove B:
Map[a:8 C:3]
Go map usage