The statement of map
Basic syntax
var map variable name map[keytype]valuetype
What type of key can be
The key of map in golang can be of many types, such as bool, number, string, pointer, channel, and interface, structure, and array containing the previous types.
Usually int, string
What type of valuetype can be
The type of valuetype is basically the same as the key, so I won't go into details here
Usually: numbers (integral, floating point number), string, map, struct
Note: slice, map and function are not allowed, because these cannot be judged using ==
Map Statement
example
var a map[string]string
var a map[string]int
var a map[string]string
var a map[string]map[string]string
Note: Declaration will not allocate memory. Initialization requires make, and the memory can only be allocated before it can be assigned and used.
- Be sure to make map before using
- The key of the map cannot be repeated. If it is repeated, the last key-value shall prevail.
- The value of the map can be the same
- The key-value of map is unordered
How to use map
func main(){ // The first type var a map[string]string // Before using map, you need to make first. The purpose of make is to allocate data space to map. a = make(map[string]string,10) a["no1"] = "Song Jiang" a["no2"] = "Wu Yong" a["no3"] = "Wu Song" // The second way cities := make(map[string]string) cities["no1"] = "Beijing" cities["no2"] = "Tianjin" cities["no3"] = "Shanghai" (cities) // The third way heroes := map[string]string{ "hero1":"Song Jiang", "hero2":"Lu Junyi", "hero3":"Wu Yong", } ("heroes=",heroes) }
use
studentMap := make(map[string]map[string]string) studentMap["stu01"] = make(map[string]string,3) studentMap["stu01"]["name"] = "tom" studentMap["stu01"]["sex"] = "male" studentMap["stu01"]["address"] = "Beijing Chang'an Street~" studentMap["stu02"] = make(map[string]string,3) studentMap["stu02"]["name"] = "mary" studentMap["stu02"]["sex"] = "female" studentMap["stu02"]["address"] = "Shanghai~" (studentMap) (studentMap["stu02"]) (studentMap["stu02"]["address"])
Map adds and updates
Map adds and updates:
map["key"] = value // If the key has not yet, it is increased, and if the key exists, it is modified.
map delete
delete(cities,"no1") (cities) // When the key specified by delete does not exist, the delete will not operate and there will be no errors// If you want to delete all keys at once// 1.Transfer all keys, how to delete them one by one [Transfer]//2. Make a new space directlycities = make(map[string]string) (cities)
map search
// Demonstrate map searchval,ok := cities["no2"] if ok{ ("There is no1 key value of %v\n",val) }else{ ("No no1 key \n") }
Explain the above code:
Note: If "no1" exists in heroes map, then findRes will return true, otherwise false
Map traversal
// Use for-range to traverse a map with a relatively complex structurestudentMap := make(map[string]map[string]string) studentMap["stu01"] = make(map[string]string,3) studentMap["stu01"]["name"] = "tom" studentMap["stu01"]["sex"] = "male" studentMap["stu01"]["address"] = "Beijing Chang'an Street~" studentMap["stu02"] = make(map[string]string,3) studentMap["stu02"]["name"] = "mary" studentMap["stu02"]["sex"] = "female" studentMap["stu02"]["address"] = "Shanghai~" for k1,v1 := range studentMap{ ("k1=",k1) for k2,v2 := range v1{ ("\t k2=%v v2=%v\n",k2,v2) } () }
The length of the map:
func len(v type) int
Map slice
Basic introduction
If the data type of slice is a map, we call it slice of map, map slice, so that the number of maps can be changed dynamically.
Case demonstration
Requirement: Use a map to record the information name and age of the monster, that is, the monster corresponds to a map, and the number of monsters can be increased in the east =》map slice
// Declare a map slicevar monsters []map[string]string monsters = make([]map[string]string,2) // Prepare to put two monsters in// Add information about the first monsterif monsters[0] == nil{ monsters[0] = make(map[string]string,2) monsters[0]["name"] = "Bul Demon King" monsters[0]["age"] = "500" } if monsters[1] == nil{ monsters[1] = make(map[string]string,2) monsters[1]["name"] = "Jade Rabbit Spirit" monsters[1]["age"] = "400" } // The following writing method goes beyond the boundaries//if monsters[2] == nil{ // monsters[2] = make(map[string]string,2) // monsters[2]["name"] = "vix" // monsters[2]["age"] = "300" //} //Define a monsters information first. You can dynamically add monster and append functions.newMonster := map[string]string{ "name":"New Monster~ Fire Cloud Evil God", "age":"200" } monsters = append(monsters,newMonster ) (monsters)
map sort
Basic introduction
- There is no special method in golang to sort map keys
- The map in golang is unordered by default, please note that it is not stored in the order of addition. Every time you traverse, the output you get may be different.
- The sorting of maps in golang is to sort the key first, and then iterate through the output according to the key value.
func main(){ // Sorting of map map1 := make(map[int]int,10) map1[10] = 100 map1[1] = 13 map1[4] = 56 map1[8] = 90 (map1) // If the output is sorted in the order of map keys // 1. First put the map key into the slice // 2. Sort slices // 3. Iterate through the slice and then output the map value according to the key var keys []int for k,_ :=range map1{ keys = append(keys,k) } // Sort (keys) (keys) for _,k := range keys{ ("map1[%v]=%v \n",k,map1[k]) } }
map usage details
- Map is a reference type, which follows the mechanism of passing parameters of reference type. When a function receives map, after modifying it, the original map will be directly modified.
- After the capacity of the map is reached, if you want to add elements to the map, it will automatically expand the capacity, and panic will not occur. That is to say, the map can dynamically grow key-value pairs (key-value)
- The value of map also often uses the struct type, which is more suitable for managing complex data (better than the previous value is a map), such as the value is a student structure
func modify(map1 map[int]int){ map1[10] = 900 } func main(){ // map is a reference type, which follows the mechanism of reference type passing, and receives map in a function // After modification, the original map will be modified directly map1 := make(map[int]int) map1[1] = 90 map1[2] = 88 map1[10] = 1 map1[20] = 2 modify(map1) // Look at the result, map1[10] = 900, indicating that map is a reference type (map1) }
Map exercises
- map type using map[string]map[string]string
- key: means the user name, it is unique and cannot be repeated
- If a username exists, change its password to 888888. If it does not exist, add this user information (including nickname nickname and password pwd)
- Write a function modifyUser(users map[string]map[string]string,name string) to complete the above function
Code implementation:
func modifyUser(users map[string]map[string]string,name string){ // Determine whether there is a name in users if users[name] != nil{ // There is this user users[name]["pwd"] = "888888" }else{ // No user users[name] = make(map[string]string,2) users[name]["pwd"] = "888888" users[name]["nickname"] = "Nickname~"+name // Demo } } func main(){ users := make(map[string]map[string]string,10) users["smith"] = make(map[string]string,2) users["smith"]["pwd"] = "999999" users["smith"]["nickname"] = "Little Cat" modifyUser(users,"tom") modifyUser(users,"mary") modifyUser(users,"smith") (users) }
This is the end of this article about the brief analysis of the implementation principle of Golang map. For more related Golang map content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!