Golang map is an unordered key-value based data structure, equivalent to dictionaries, hash, HashTable, etc., in other programming languages.
Key (index) corresponds to value (value), given the key (index) can quickly query the corresponding value (value) data structure.
The map definition
The syntax of map is as follows:
map[KeyType]ValueType
- The KeyType:
key
The type of. - ValueType: indicates the corresponding key
value
The type of.
The map variable starts as nil and requires the built-in make() function to allocate memory:
make(map[KeyType]ValueType, [cap])
The maximum capacity of the MAP can be dynamically increased. Therefore, cap is optional. Map is nil when uninitialized, and its length can be obtained using len().
func main(a) {
scoreMap := make(map[string]int)
scoreMap["zhangsan"] = 90
scoreMap["lisi"] = 100
fmt.Println(scoreMap) // map[lisi:100 zhangsan:90]
fmt.Println(scoreMap["lisi"]) / / 100
fmt.Printf("type of a:%T\n", scoreMap) // type of a:map[string]int
}
Copy the code
Map also supports padding elements at declaration time, for example:
func main(a) {
userInfo := map[string]string{
"username": "zhangsan"."password": "123456",
}
fmt.Println(userInfo)
}
Copy the code
Use the map
Check whether a key is included
value, isExist := map[key]
- IsExist is false if it does not exist
- Value indicates the value of the key
Traverse map
Note: The order in which the map is traversed is independent of the order in which it was added.
func main(a) {
scoreMap := make(map[string]int)
scoreMap["zhangsan"] = 90
scoreMap["lisi"] = 100
scoreMap["wangwu"] = 60
for k, v := range scoreMap {
fmt.Println(k, v)
}
}
Copy the code
The delete() function deletes key-value pairs
Delete (map, key) // map: deletes the map of key-value pairs. Key: deletes the key