1. What is map
Map is an unordered collection of key-value pairs. The most important thing about Map is to quickly retrieve data through keys. Key is similar to indexes and points to the value of data.
Map is unordered and we cannot decide the order of its return, because Map is implemented using hash tables
Map is a reference type and must be initialized to use. Among them, except for reference types such as slices, all types of keys can be used; while value can use all types of values.
2. Create a map
You can create a map through make(), which will first create the underlying data structure, then create the map, and let the map point to the underlying data structure
my_map := make(map[string]int)
[string] The data type of the map key
int represents the value corresponding to the key
Create and initialize the assignment directly through braces:
// Empty mapmy_map := map[string]string{} // Initialize the assignmentmy_map := map[string]string{"Red": "#da1337","Orange": '#e95a22"} // Format assignmentmy_map := map[string]int{ "Java":11, "Perl":8, "Python":13, // Note that the ending commas cannot be missing}
Notice:
The map's key can be any built-in data type (such as int), or other data types that can be compared with equal values by ==, such as interface and pointer, and slice, array, map, and struct types cannot be used as keys, and the key must be unique.
But the value can basically be of any type, such as nesting a slice into a map:
my_map := map[string][]int{}
3. Access map
When accessing an element in a map, just specify its key. Note that the key of the string type must be quoted:
package main import "fmt" func main() { my_map := map[string]int{ "1": 10, "2": 20, "3": 30, "4": 40, } //access (my_map["1"]) (my_map) ("") //Assign existing key & value my_map["2"] = 50 (my_map["2"]) (my_map) ("") // Assign new key&value my_map["5"] = 66 (my_map["5"]) (my_map) }
Output result
10
map[1:10 2:20 3:30 4:40]
50
map[1:10 2:50 3:30 4:40]
66
map[1:10 2:50 3:30 4:40 5:66]
4. nil map and empty map
An empty map is a map that does not do any assignment:
// Empty mappackage main import "fmt" func main() { my_map := map[string]string{} (my_map) }
Output result
map[]
nil map, it will not do any initialization and will not point to any data structure:
// nil map var my_map map[string]string
The relationship between nil map and empty map is just like nil slice and empty slice. Both are empty objects and do not store any data. However, the former does not point to the underlying data structure, and the latter points to the underlying data structure, but the underlying object pointed to is an empty object.
Use println output to see:
package main func main() { var nil_map map[string]string println(nil_map) emp_map := map[string]string{} println(emp_map) }
Output result:
0x0
0xc04204de38
So, the map type is actually a pointer.
5. Return value of element in map
When accessing an element in a map, there are two formats for returning values:
value := my_map["key"] value,exists := my_map["key"]
The first one is easy to understand, which is to retrieve the value corresponding to the key in the map. If the key does not exist, the value returns 0 of the corresponding data type. For example, int is the value 0, boolean is false, and the string is empty "".
The second type not only returns the value corresponding to the key, but also returns a boolean value to the exists variable based on whether the key exists. Therefore, when the key exists, the value is the corresponding value, and exists is true; when the key does not exist, the value is 0 (also represented by 0 by each data type), and exists is false.
See the following example:
package main import "fmt" func main() { my_map := map[string]int{ "1": 10, "2": 20, "3": 30, "4": 40, } a := my_map["1"] b, exists1 := my_map["2"] c, exists2 := my_map["5"] (a) (b, exists1) (c, exists2) }
The above outputs the following result:
10
20 true
0 false
There are many cases where multiple return values are set in Go, and even if you write your own function, it will often set its exists attribute.
6. len() and delete()
The len() function is used to get the number of elements in the map, that is, there are multiple small keys. delete() is used to delete a key in the map.
package main import "fmt" func main() { my_map := map[string]int{ "1": 10, "2": 20, "3": 30, "4": 40, } ("The length before deletion is %d\n", len(my_map)) delete(my_map, "1") ("Length after deletion is %d", len(my_map)) }
The output result is as follows
The length before deletion is 4
The length after deletion is 3
7. Test whether the element in the map exists
There are two ways to test whether a key exists in the map:
①Judge according to the second return value of the map element
② Judging by whether the returned value is 0 (0 for different data types is different)
Method 1: Directly access the element in the map and assign it to two variables. The second variable is the modified variable whether the element exists.
package main import "fmt" func main() { my_map := map[string]int{ "1": 10, "2": 20, "3": 30, "4": 40, } //Method 1/* value, exists := my_map["1"] if exists { ("exist", value) } */ //Method 2 if value, exists := my_map["1"]; exists { ("The value exists, value=%d", value) } }
The output result is as follows
The value exists, value=10
Method 2: judge based on the value returned by the map element. Because the value part in the map is of type int, its 0 is the 0 of the numeric value.
package main import "fmt" func main() { my_map := map[string]int{ "1": 10, "2": 20, "3": 30, "4": 40, } value := my_map["5"] if value == 0 { ("Not exists") } }
The output result is as follows
Does not exist
If the value data type of map is string, it is determined whether it is empty:
package main import "fmt" func main() { my_map := map[string]string{ "1": "book", "2": "games", "3": "computer", } value := my_map["5"] if value == "" { ("Not exists") } }
The output result is as follows
Does not exist
Since the value in the map may exist itself, but its value is 0, a misjudgment will occur. For example, the following "3" already exists, but its corresponding value is 0
package main import "fmt" func main() { my_map := map[string]int{ "1": 22, "2": 11, "3": 0, } value := my_map["3"] if value == 0 { ("Not exists") } }
The output result is as follows
Does not exist
Therefore, the first method should be used to determine whether the element exists.
8. Iterative traversal map
Because map is a data structure of key/value type, key is the index of map, so when the range keyword operates on map, the key and value will be returned.
package main import "fmt" func main() { my_map := map[string]int{ "1": 22, "2": 11, "3": 0, "4": 55, "5": 66, } for k, v := range my_map { ("key=%s, value=%d\n", k, v) } }
The output result is as follows
key=1, value=22
key=2, value=11
key=3, value=0
key=4, value=55
key=5, value=66
If range iterates over the map, only one return value is given, it means the key of the iterated map:
package main import "fmt" func main() { my_map := map[string]int{ "1": 22, "2": 11, "3": 0, "4": 55, "5": 66, } for key := range my_map { ("key=", key) } }
Output result
key= 1
key= 2
key= 3
key= 4
key= 5
9. Get all keys in the map
There is no function in Go that directly gets all keys of map. Therefore, you can only write it yourself. The method is very simple. Range traverse the map and put the traversed key into a slice to save it.
package main import "fmt" func main() { my_map := map[string]int{ "Java": 11, "Perl": 8, "Python": 13, "Shell": 23, } // Save the slice of the key in the map // The slice type must be consistent with the map key type keys := make([]string,0,len(my_map)) // traverse the keys in the map into keys for map_key,_ := range my_map { keys = append(keys,map_key) } (keys) }
Note that the slice declared above should limit the length to 0, otherwise it is declared as a slice of length 4 and capacity 4. These 4 elements are all empty values. Moreover, the slice after append() will directly expand the slice once, resulting in the slice length after append() being twice the length of the map, the first half is empty, and the latter is generally the key in the map.
10. Pass map to function
Map is a pointer, so passing the map to a function is just copying this pointer, so the operation of the map inside the function will directly modify the external map.
For example, test() is used to add 1 to the corresponding value of the map key.
package main import "fmt" func main() { my_map := map[string]int{ "1": 22, "2": 11, "3": 0, "4": 55, "5": 66, } ("Before modificationkey=", my_map["3"]) (my_map) ("") test(my_map, "3") ("After modificationkey=", my_map["3"]) (my_map) } func test(m map[string]int, key string) { m[key] += 1 }
The output result is as follows
Before modifying key= 0
map[1:22 2:11 3:0 4:55 5:66]
After modification key= 1
map[1:22 2:11 3:1 4:55 5:66]
This is the end of this article about the detailed explanation of the usage of Go language learning mapping (map). For more related Go language mapping content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!