Go map

Go map is an unordered sequence based on the key-value data structure. It is a reference type and must be initialized before use.

Map Definition

Regular Definition๏ผš

    var s1 map[KeyType]ValueType
or
    s1 := map[KeyType]ValueType{}

Using make๏ผš

    var s2 map[KeyType]ValueType = make(map[KeyType]ValueType, initialCapacity)
or
    s2 := make(map[KeyType]ValueType, initialCapacity)

Where KeyType is the type of the key, ValueType is the type of the value, and initialCapacity is an optional parameter used to specify the initial capacity of the Map. When the number of key-value pairs in the Map reaches its capacity, the Map will automatically expand. If initialCapacity is not specified, Go will choose a suitable value based on the actual situation.

userList := make(map[string]int, 2)
userList["Flasle"] = 18
userList["Synfun"] = 19
userList["Valinv"] = 20 //Upon exceeding the capacity, Go will automatically expand the Map

fmt.Println("userList:", userList)
fmt.Println("Flasle age:", userList["Flasle"])
fmt.Println("Size:", len(userList))
fmt.Printf("type of it: %T\n", userList)

#userList: map[Flasle:18 Synfun:19 Valinv:20]
#Flasle age: 18
#Size: 3
#type of it: map[string]int

Maps support filling elements (initialization) during declaration:

userList := map[string]int{
    "Flasle": 18,
    "Synfun":  19,
    "Valinv":  20,
}

Retrieving elements from a Map

If the key exists, ok is true, and value is the corresponding value; if not, ok is false, and value is the default value for the value type.

value, ok := mapVariable[key]

Map Traversal

for key, value := range mapVariable {
   //...
}

Deleting elements from a Map

delete(mapVariable, key)

 

Take a break

๐Ÿ‘‰๐Ÿ‘‰๐Ÿ‘‰ ใ€BTTH Year EP97ใ€‘Xiao Yan vs Fei Tian, and then understood Three Thousand Lightning Movement