SoFunction
Updated on 2025-03-05

GO Language Map (Map) Usage Analysis

This article describes the usage of GO language mapping (Map). Share it for your reference. The details are as follows:

Mapping is a built-in data structure that saves an unordered set 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}

As follows, create arrays in 4 ways. The difference between the first and the second is whether the initial capacity is specified, but you don’t need to pay attention to these when using them, because the nature of the map determines that once the capacity is insufficient, it will automatically expand:

Copy the codeThe code is 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"}
    (map1, map2, map3, map4)
}

The output is as follows:

map[] map[] map[] map[c:3 a:1 b:2]

(2) Map fill and traversal

Copy the codeThe code is as follows:
func test2() {
    map1 := make(map[string]string)
    map1["a"] = "1"
    map1["b"] = "2"
    map1["c"] = "3"
    for key, value := range map1 {
        ("%s->%-10s", key, value)
    }
}

As mentioned above, the array is filled with map[key] = value. When traversing the map, each item returns 2 values, keys and values. The results are as follows:

a->1    b->2    c->3   

(3) Search, modify and delete maps

Copy the codeThe code is as follows:
func test3() {
    map4 := map[string]string{"a": "1", "b": "2", "c": "3"}
    val, exist := map4["a"]
    val2, exist2 := map4["d"]
    ("%v,%v\n", exist, val)
    ("%v,%v\n", exist2, val2)

map4["a"] = "8" //There is no difference between modifying the mapping and adding the mapping
    ("%v\n", map4)

("Delete b:")
    delete(map4, "b")
    ("%v", map4)
}

When a map specifies that the key takes the corresponding value, it can specify that two values ​​are returned, the first is the corresponding value and the second is a bool, indicating whether there is a value. As mentioned above, "a" must have a value, and "b" must have no value.

There is no difference between modifying a map and adding a map. If the specified key does not exist, it will be created, otherwise, it will be modified.

Delete is to use the built-in function delete 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 this article will be helpful to everyone's GO language programming.