Go Language Dictionary (map) usage example analysis [create, fill, traverse, search, modify, delete]


This paper gives an example of the usage of go Language Dictionary (map). To share with you for your reference, as follows:

A dictionary is a built-in data structure that holds an unordered collection of key value pairs.

(1) Dictionary creation

1) make(map[KeyType]ValueType, initialCapacity)
2) make(map[KeyType]ValueType)
3) map[KeyType]ValueType{}
4) map[KeyType]ValueType{key1 : value1, key2 : value2, ... , keyN : valueN}

As follows, there are four ways to create arrays respectively. The first one and the second one differ from each other in that whether the initial capacity is specified or not, but you don’t need to care about it when you use it, because the nature of map determines it,Once the capacity is not enough, it will automatically expand

Copy 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”}
    fmt.Println(map1, map2, map3, map4)


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

(2) Dictionary filling and traversal: for range

Copy 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 {
        fmt.Printf(“%s->%-10s”, key, value)

As above, array padding usesmap[key] = value When traversing the dictionary, each item will return 2 values, keys and values. The results are as follows:

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

(3) Find, modify, and delete Dictionaries: delete()

Copy 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”]
    fmt.Printf(“%v,%v\n”, exist, val)
    fmt.Printf(“%v,%v\n”, exist2, val2)
Map4 [“a”] = “8” / / there is no difference between modifying a dictionary and adding a dictionary
    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, it can specify to return two values, the first is the corresponding value, and the second is a bool, indicating whether there is a value. As above, “a” must be worth it, and “B” must not be.

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

Delete is the built-in function of godelete(), the output is as follows:

map[a:8 b:2 c:3]
Delete B:
map[a:8 c:3]

To access the dictionary, it is safer to:

Copy codeThe code is as follows:
map4 := map[string]string{“a”: “1”, “b”: “2”, “c”: “3”}
val, exist := map4[“d”]
if exist {
} else {
    fmt.Println(“not exists”)

I hope that this paper will be helpful for you to design the go language program.