map is an unordered key-value pair, which is an implementation method of the hash table in the data structure. The way map works is to define keys and values, and you can get, set and delete the values in them.
statement
// Use the keyword map to declarebMap := map[string]int{"key1": 18} // Use make to declarecMap := make(map[string]int) cMap["key2"] = 19 ("bMap:", bMap) ("cMap:", cMap)
The above program creates two maps in two ways, and the running results are as follows:
bMap: map[key1:18]
cMap: map[key2:19]
Search the value of the key
The syntax for searching Map elements ismap[key]
aMap := make(map[string]int) aMap["key1"] = 18 aMap["key2"] = 19 ("aMap:", aMap) ("aMapkey2:", aMap["key2"]) ("aMapkey3:", aMap["key3"])
When the key does not exist in the map, the map returns the zero value of the element type. So the above program output is:
aMap: map[key1:18 key2:19]
aMapkey2: 19
aMapkey3: 0
Search for keys exist
The syntax to retrieve whether the key exists isvalue, ok := map[key]
aMap := make(map[string]int) aMap["key1"] = 18 aMap["key2"] = 19 value, ok := aMap["key3"] if ok { ("key3", value) } else { ("key3", "no") }
ok
The value of the map is whether the key exists, and it exists astrue
, otherwisefalse
. Therefore, the output of the above program is: key3 no
Iterate through all elements in the map
You can use the range form of a for loop to iterate through all elements of a Map.
aMap := make(map[string]int) aMap["key1"] = 18 aMap["key2"] = 19 for key, value := range aMap { ("aMap[%s] = %d\n", key, value) }
The above program output is:
aMap[key1] = 18
aMap[key2] = 19
Because maps are unordered, for each execution of the program, it is not guaranteed that the order of traversing maps using for range is always consistent, and the order of traversals is not exactly consistent with the order of elements being added.
Remove elements from Map
delete(map, key)
Used to delete keys in map. The delete function does not return a value.
aMap := make(map[string]int) aMap["key1"] = 18 aMap["key2"] = 19 ("map before deletion", aMap) delete(aMap, "key1") ("map after deletion", aMap)
The above program output is:
map before deletion map[key1:18 key2:19]
map after deletion map[key2:19]
This is the article about the example code of map addition, deletion, modification and search in golang. For more related contents of map addition, deletion, modification and search, please search for my previous articles or continue to browse the related articles below. I hope everyone will support me in the future!