The mapping container provided by Go language is Map, which uses hash internally.

A map is an unordered collection of key-value pairs. The most important thing about a map is that it quickly retrieves data through keys. Keys are similar to indexes, values that point to data. A map is a collection, so you can iterate over it like an array or slice. However, the map is unordered and the order in which it is returned cannot be determined. This is because the map is implemented using a hash table. In the Go language, a map is a reference type and must be initialized to be used.

Note the following points when using MAP:

  • The map is unordered, and the printed map is different each time. The map cannot be obtained by index, but must be obtained by key
  • A map is of variable length, which, like slice, is a reference type
  • The built-in len function also applies to maps, returning the number of keys the map has
  • The map key can be allA comparable typeBoolean, integer, floating point, complex, string… You can also bond.

define

The map definition syntax in Go language is as follows:

map[KeyType]ValueType
Copy the code

Among them,

  • KeyType: Indicates the type of the key.
  • ValueType: indicates the type of the value corresponding to the key.

** Variables of type map default to nil and require the make() function to allocate memory (declared and initialized) **. Grammar:

make(map[KeyType]ValueType, [cap])
Copy the code

Cap represents the capacity of the map. This parameter is not required, but an appropriate capacity should be specified when the map is initialized.

A map can be defined using either the built-in function make or the map keyword:

/* Declare variables, default map is nil */
var mapVariable map[KeyType]ValueType

/* Use make function */
mapVariable = make(map[keyType]ValueType)
rating := map[string]float32 {"C":5."Go":4.5."Python":4.5."C++":2 }
Copy the code

If the map is not initialized, a nil map is created. Nil maps cannot be used to hold key-value pairs

The basic use

The data in the map comes in pairs:

func main(a) {
 scoreMap := make(map[string]int.8)
 scoreMap["Zhang"] = 90
 scoreMap["Xiao Ming"] = 100
 fmt.Println(scoreMap)
 fmt.Println(scoreMap["Xiao Ming"])
 fmt.Printf("type of a:%T\n", scoreMap)
}
Copy the code

Output:

100 type of a:map[string]intCopy the code

Map also supports padding elements at declaration time, for example:

func main(a) {
 userInfo := map[string]string{
  "username": "Zhang"."password": "123456",
 }
 fmt.Println(userInfo) //
}
Copy the code

Check whether the key exists

In Go, there is a special way to determine whether a key exists in a map. The format is as follows:

value, ok := map[key]
func main(a) {
 /* Create a collection */
   countryCapitalMap := make(map[string]string)
   
   /* map inserts key-value pairs, capital of each country */
   countryCapitalMap["France"] = "Paris"
   countryCapitalMap["Italy"] = "Rome"
   countryCapitalMap["Japan"] = "Tokyo"
   countryCapitalMap["India"] = "New Delhi"
 // if key exists, ok is true and v is the corresponding value; There is no zero value where OK is false and v is a value type
 v, ok := countryCapitalMap["United States"]
 if ok {
  fmt.Println("Capital of United States is", captial)  
   }else {
      fmt.Println("Capital of United States is not present")}}Copy the code

The map of traverse

Go uses for range to traverse a map.

func main(a) {
 countryCapitalMap := make(map[string]string)
   /* map inserts key-value pairs, capital of each country */
   countryCapitalMap["France"] = "Paris"
   countryCapitalMap["Italy"] = "Rome"
   countryCapitalMap["Japan"] = "Tokyo"
   countryCapitalMap["India"] = "New Delhi"
 for k, v := range countryCapitalMap {
  fmt.Println(k, v)
 }
}
Copy the code

When you just want to iterate over a key, you can write:

func main(a) {
 countryCapitalMap := make(map[string]string)
   /* map inserts key-value pairs, capital of each country */
   countryCapitalMap["France"] = "Paris"
   countryCapitalMap["Italy"] = "Rome"
   countryCapitalMap["Japan"] = "Tokyo"
   countryCapitalMap["India"] = "New Delhi"
 for k := range countryCapitalMap {
  fmt.Println(k)
 }
}
Copy the code

Note: The order in which the elements are iterated through the map is independent of the order in which the key-value pairs are added.

The delete() function deletes map elements

Delete a set of key-value pairs from a map using the delete() built-in function. The delete() function returns no value. The format of the delete() function is as follows:

delete(map, key)
Copy the code

Among them,

  • map: indicates the map to delete key-value pairs
  • key: Indicates the key of the key-value pair to be deleted
func main(a){
 countryCapitalMap := make(map[string]string)
   /* map inserts key-value pairs, capital of each country */
   countryCapitalMap["France"] = "Paris"
   countryCapitalMap["Italy"] = "Rome"
   countryCapitalMap["Japan"] = "Tokyo"
   countryCapitalMap["India"] = "New Delhi"
 delete(countryCapitalMap, "France")// Delete "France":"Paris" from map
 for k,v := range scoreMap{
  fmt.Println(k, v)
 }
}
Copy the code

Specifies the order to traverse the map

func main(a) {
 rand.Seed(time.Now().UnixNano()) // Initializes the random number seed

 var scoreMap = make(map[string]int.200)

 for i := 0; i < 100; i++ {
  key := fmt.Sprintf("stu%02d", i) // Generate a string beginning with stu
  value := rand.Intn(100)          // Generate random integers from 0 to 99
  scoreMap[key] = value
 }
 // Remove all keys from map and store them in slice keys
 var keys = make([]string.0.200)
 for key := range scoreMap {
  keys = append(keys, key)
 }
 // Sort the slices
 sort.Strings(keys)
 // Traverses the map according to the sorted key
 for _, key := range keys {
  fmt.Println(key, scoreMap[key])
 }
}
Copy the code

Slice of map type

The following code slice works when the elements are of type map:

func main(a) {
 var mapSlice = make([]map[string]string.3)
 for index, value := range mapSlice {
  fmt.Printf("index:%d value:%v\n", index, value)
 }
 fmt.Println("after init")
 // Initialize the map element in the slice
 mapSlice[0] = make(map[string]string.10)
 mapSlice[0] ["username"] = "Zhang"
 mapSlice[0] ["password"] = "123456"
 mapSlice[0] ["address"] = "Shenzhen"
 for index, value := range mapSlice {
  fmt.Printf("index:%d value:%v\n", index, value)
 }
}
Copy the code

Value indicates the map of the slice type

The following code demonstrates an operation with a value of slice type in a map:

func main(a) {
 var sliceMap = make(map[string] []string.3)
 fmt.Println(sliceMap)
 fmt.Println("after init")
 key := "China"
 value, ok := sliceMap[key]
 if! ok { value =make([]string.0.2)
 }
 value = append(value, "Beijing"."Shanghai")
 sliceMap[key] = value
 fmt.Println(sliceMap)
}
Copy the code

Map is a reference type

Like slices, a map is a reference type. When a map is assigned to a new variable, they all point to the same internal data structure. Thus, a change in one reflects the other:

func main(a) {  
    personSalary := map[string]int{
        "steve": 12000."jamie": 15000,
    }
    personSalary["mike"] = 9000
    fmt.Println("Original person salary", personSalary)
    newPersonSalary := personSalary
    newPersonSalary["mike"] = 18000
    fmt.Println("Person salary changed", personSalary)

}
Copy the code

Running results:

Original person salary map[steve:12000 jamie:15000 mike:9000]  
Person salary changed map[steve:12000 jamie:15000 mike:18000] 
Copy the code

Maps cannot be compared using operators. It can only be used to check whether the map is empty. Invalid operation: map1 == map2 (map can only be comparedto nil)