GO language summary (4) - map (Map)

Previous blog describes the array and slice Go languages - GO language summary (3) - and an array of slices , this blog describes the mapping Go Language (Map)

Mapping is a built-in data structures used to store a set of key-value pairs disorder.

(1) create mapping

make ( map [KeyType] ValueType, initialCapacity )

make ( map [KeyType] ValueType )

map [KeyType ] ValueType {}

map [KeyType ] ValueType { key1 : value1, key2: value2, ... , keyN : valueN}

As follows, respectively with 4 ways to create an array, where the difference between first and second is that there is no specified initial capacity, but when you do not need to use care about them, because of the nature of the decision of the map, once the capacity is not enough, it will automatic expansion:

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)
}

 

Output is as follows:

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

 

(2) filling map, and traverse

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 populated with map [key] = value way, the traversal mapping, each of which returns two values, keys and values. The results are as follows:

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

 

(3) map to find, edit, and delete

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 the mapping and adding a mapping no difference 
    fmt.Printf ( " % V \ n- " , MAP4) 

    fmt.Println ( " Delete B: " ) 
    Delete ( MAP4, " B " ) 
    fmt.Printf ( " % V " , MAP4) 
}

When the map corresponding to the specified key value taken, can be specified return two values, corresponding to a first value, the second is a BOOL, indicating whether or not the value. Above, "a" must have value, "b" is certainly no value.

Modify the mapping and mapping add operations no difference, if the specified key does not exist, create, or modify it.

Delete the go using built-in functions delete, output is as follows:

 

to true , . 1 
to false , 
Map [A: . 8 B: 2 C: . 3 ] 
Delete B: 
Map [A: . 8 C: . 3 ]

 

 

Reference: "Go Programming Language"

Reproduced in: https: //www.cnblogs.com/zrtqsk/p/4150129.html

Guess you like

Origin blog.csdn.net/weixin_34121304/article/details/93248552