Mapping of Go Language-map
[TOC]
- Like hash tables or dictionaries in other languages, data is stored in key-value form
- Key must be a type that supports == or!= comparison operations, not a function, map, or slice; value can be of any type.
- Map lookup is much faster than linear search, but 100 times slower than the type of data accessed using an index
- Map is created using make() to support: = this abbreviation
- make(map[keyType]valueType, cap), cap represents capacity, can be omitted
- It will expand automatically when it exceeds capacity, but try to provide a reasonable initial value and apply for memory in advance, which will help improve performance.
- Use len() to get the number of elements
- Automatically add key pairs when they do not exist, delete a key pair with delete()
- Use for range to iterate over map and slice
Map introduction
The map in go language is a data structure used to store some disordered key-value pairs. Map is an unordered collection because it has a hash table (hash table) at the bottom. The key of map can support the type of comparison operation as long as it supports== or!=, but it can not be compared by functions, maps, slice s, etc. Value can be of any type.
1. Map Creation
1.1 Use make function
// Create a mapping where the key type is string and the value type is int dict := make(map[string]int)
make(map[keyType]valueType, cap),cap represents capacity. It can specify a reasonable initial capacity size at the time of creation, so that a large chunk of memory will be applied, avoiding frequent expansion and waste of performance in subsequent use. For example: m: = make (map [string] int, 1000)
1.2 Create with literal values
// Create a mapping with keys and values of string types // Initialize the mapping using two key-value pairs dict := map[string]string{"Red": "#da1337", "Orange": "#e95a22"}
2. Use mapping
2.1 Assignment of Maps
// Create an empty map to store the color and the hexadecimal code corresponding to the color colors:=map[string]string{} // Add Red's code to the mapping colors["Red"]="#da1337"
2.1 uninitialized map, assignment error, nil map
// Create a nil map by declarative mapping var colors map[string]string // Add Red's code to the mapping colors["Red"] = "#da1337" Runtime Error: panic: runtime error: assignment to entry in nil map
2.2 Get the value from map and determine whether the key exists
Because of the multiple return values of go, when map gets the value, it will return the value, and a boolean parameter, which means that it is not successful, is there, right?
In the Go language, when the mapping is indexed by a key, a value is always returned even if the key does not exist. In this case, the zero value of the type corresponding to the value is returned.
// Get the value corresponding to the key Blue value, exists := colors["Blue"]// Does this bond exist? if exists { fmt.Println(value) } //Of course, it can be judged directly by the zero value of the type - it's the same. // Get the value corresponding to the key Blue value := colors["Blue"] // Does this bond exist? if value != "" { fmt.Println(value) }
2.3 Iterating map with range
// Create a mapping to store the color and the hexadecimal code corresponding to the color colors := map[string]string{ "AliceBlue": "#f0f8ff", "Coral": "#ff7F50", "DarkGray": "#a9a9a9", "ForestGreen": "#228b22", } // Display all the colors in the map for key, value := range colors { fmt.Printf("Key: %s Value: %s\n", key, value) } //
range iteration is the same as array and slice, except that the key-value pair of map is returned here, while array, slice returns index and value.
delete function in 2.4 map
The delete(map,key) function can delete the key pair of the specified key from the map. This method can only be used when the values stored in the mapping are all non-zero values.
// Delete key-value pairs whose keys are Coral delete(colors, "Coral") // Display all the colors in the map for key, value := range colors { fmt.Printf("Key: %s Value: %s\n", key, value) }
2.5 map as parameter transfer
Like slice, they are reference types that point to the underlying data structure. Slice points to arrays and map points to hash tables. When map passes between functions as parameters, it copies the map pointer, the value copy relative to the pointer, and the reference transfer relative to the underlying layer. In fact, I think that all the pass of go is value transfer, but some values are value, and some values are pointers.
So, passing map in the function and modifying map will modify the underlying data.
// removeColor deletes keys from the specified map func removeColor(colors map[string]string, key string) { delete(colors, key) }
// Create a mapping to store the color and the hexadecimal code corresponding to the color colors := map[string]string{ "AliceBlue": "#f0f8ff", "Coral": "#ff7F50", "DarkGray": "#a9a9a9", "ForestGreen": "#228b22", } // Display all the colors in the map for key, value := range colors { fmt.Printf("Key: %s Value: %s\n", key, value) } fmt.Println() // Call a function to remove the specified key removeColor(colors, "Coral") // Display all the colors in the map for key, value := range colors { fmt.Printf("Key: %s Value: %s\n", key, value) } //Output result Key: AliceBlue Value: #F0F8FF Key: Coral Value: #FF7F50 Key: DarkGray Value: #A9A9A9 Key: ForestGreen Value: #228B22 Key: AliceBlue Value: #F0F8FF Key: DarkGray Value: #A9A9A9 Key: ForestGreen Value: #228B22
Common operations of map
m := map[string]int{ "a": 1, } if v, ok := m["a"]; ok { // Determine whether the key exists. println(v) } println(m["c"]) // For nonexistent key s, return directly to 0 without error. m["b"] = 2 // Add or modify. delete(m, "c") // Delete. If the key does not exist, there will be no error. println(len(m)) // Gets the number of key pairs. cap effect. for k, v := range m { // Iteration, only key can be returned. Random sequence return, each time is different. println(k, v) }
3. The value extracted from the map is a copy, and there is no sense in modifying its members.
type user struct{ name string } m := map[int]user{ // When map is re-hashed due to expansion, the storage location of key items will change. Therefore, map 1: {"user1"}, // It is designed as not addressable. Expectations like m[1].name pass through the original value } // Pointer modification of members to will be banned. m[1].name = "Tom" // Error: cannot assign to m[1].name
Because a copy of a user instance is taken out, its members cannot be modified directly. If it is implemented, there are two ways.
3.1 Complete replacement of this value
u := m[1] u.name = "Tom" m[1] = u // Replace value.
3.2 Use pointers
m2 := map[int]*user{ 1: &user{"user1"}, } m2[1].name = "Jack" // The return is a copy of the pointer. It is permissible to modify the original object through the pointer.