This is the sixth day of my participation in the August More text Challenge. For details, see:August is more challenging

Today we’ll move on to the next type, a Map, which is an unordered set of key-value pairs. The most important thing about a Map is that it allows you to quickly retrieve data using a key, which is like an index, a value that points to the data. A Map is a collection, so we can iterate over it the same way we iterate over arrays and slices. Maps are unordered, and we cannot determine the order in which they are returned, because maps are implemented using hash tables and are reference types.

Some points to note when using map:

  • The map is unordered. Every time the map is printed, it will be different. It cannot be obtained by index, but by key
  • Map has a variable length and is a reference type, just like slice
  • The built-in len function also applies to maps, returning the number of keys the map has
  • The key of a map can be any comparable type, such as Boolean, integer, floating point, integer, or string.

Create a Map

You can define a map using the built-in make function or using the map keyword:

/* Declare variables. The default map is nil */
var map_variable map[key_data_type]value_data_type

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

If you don’t initialize the map, then a nil map will be created. Nil map cannot be used to store key-value pairs.

package main

import "fmt"

func main(a) {
   var countryCapitalMap map[string]string
   /* Create collection */
   countryCapitalMap = make(map[string]string)
   
   /* map Insert key-value pairs, the capital of each country */
   countryCapitalMap["France"] = "Paris"
   countryCapitalMap["Italy"] = "Rome"
   countryCapitalMap["Japan"] = "Tokyo"
   countryCapitalMap["India"] = "New Delhi"
   
   /* Use key to output map */
   for country := range countryCapitalMap {
      fmt.Println("Capital of",country,"is",countryCapitalMap[country])
   }
   
   /* Check whether the element exists in the collection */
   captial, ok := countryCapitalMap["United States"]
   /* If ok is true, it exists, otherwise it does not exist. In go, if it does not exist, it returns the default value of the corresponding value type, so it is recommended to use OK to judge */
   if(ok){
      fmt.Println("Capital of United States is", captial)  
   }else {
      fmt.Println("Capital of United States is not present")}}Copy the code

Running result:

Capital of France is Paris
Capital of Italy is Rome
Capital of Japan is Tokyo
Capital of India is New Delhi
Capital of United States is not present
Copy the code

The delete () function

The delete(map, key) function deletes the elements of a collection, taking a map and its corresponding key. The delete function does not return any value.

package main

import "fmt"

func main(a) {   
   /* Create map */
   countryCapitalMap := map[string] string {"France":"Paris"."Italy":"Rome"."Japan":"Tokyo"."India":"New Delhi"}

   fmt.Println("The original map")   

   /* Print map */
   for country := range countryCapitalMap {
      fmt.Println("Capital of",country,"is",countryCapitalMap[country])
   }

   /* Delete element */
   delete(countryCapitalMap,"France");
   fmt.Println("Entry for France is deleted")  

   fmt.Println("Map after deleting elements")   

   /* Print map */
   for country := range countryCapitalMap {
      fmt.Println("Capital of",country,"is",countryCapitalMap[country])
   }
}
Copy the code

Running result:

The originalmap
Capital of France is Paris
Capital of Italy is Rome
Capital of Japan is Tokyo
Capital of India is New Delhi
Entry forFrance is deleted After the element is deletedmap
Capital of Italy is Rome
Capital of Japan is Tokyo
Capital of India is New Delhi
Copy the code

ok-idiom

We can use the key to get the corresponding value in the map. Grammar:

map[key]
Copy the code

But when the key does not exist, we get the default value for the value type, such as an empty string for string and a 0 for int. But the program doesn't report any errors.

So we can use the ok-idiom to get the value, to see if the key/value exists

value, ok := map[key]
Copy the code

Example code:

package main

import (
    "fmt"
)

func main(a) {
    m := make(map[string]int)
    m["a"] = 1
    x, ok := m["b"]
    fmt.Println(x, ok)
    x, ok = m["a"]
    fmt.Println(x, ok)
}
Copy the code

Running result:

0 false
1 true
Copy the code

The length of the map

The len function determines the length of the map.

len(map)  // You can get the length of the map
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. Therefore, changes in one reflect changes in the other.

Example code:

package main

import (  
    "fmt"
)

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 result:

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 the == operator. == Can only be used to check whether the map is empty. Invalid operation: map1 == map2 (map can only be comparedto nil)

Example code:

package main

import "fmt"

func main(a) {
    /* A map, which is used to store key-value pairs, is also called A mapping item. Var map name map[key type]value type = nil; var map name map[key type] nil; Only the map name is declared := map[key type] Value type {key:value,key:value.... Make (map[key]value) B: Make (map[key]value) B: Make (map[key]value) B: Make (map[key]value) C: Ok := map[key] If key exists, value is the corresponding value,ok is true, if key does not exist, value is the default value of the type,ok is false Delete a mapping item delete(map, key) If the key exists, the deletion succeeds. Otherwise, the deletion fails */

    //1. Define a map
    var map1 map[int]string // A map is defined, but the map has not yet been created and is nil
    map2 := map[string]int{"Go": 88."C": 98."Java": 79."Python": 85."C++": 68}
    map3 := make(map[string]int)
    fmt.Println(map1) //map[]
    fmt.Println(map2) //map[Java:79 Python:85 C++:68 Go:88 C:98]
    fmt.Println(map3) //map[]

    / / 2. Nil map
    fmt.Println(map1 == nil) // true
    fmt.Println(map2==nil)//false
    fmt.Println(map3==nil)//false

    //map1[key]=value
    if map1 == nil{
        fmt.Println("Map1 is nil, you have to create...")
        map1 = make(map[int]string)
        fmt.Println(map1 == nil)}//3. Add a mapping item to the map: Map name [key] = value
    map1[1] = "Rose"
    map1[2] = "Jack"
    map1[3] = "lala"
    fmt.Println(map1)

    // 4. Obtain the data in the map and obtain the value based on the key.

    fmt.Println(map1[1]) //Rose
    fmt.Println(map1[10]) // If the key does not exist, the result is the zero value of the value type, the default value, ""
    fmt.Println(map3)
    fmt.Println(map3["aa"])

    //value, ok := map[key]
    val1 ,ok := map1[10]
    if ok == true{
        fmt.Println("The data obtained are:",val1)
    }else{
        fmt.Println("Data cannot be obtained because key does not exist.")}//5. Delete key and value pairs in the map
    fmt.Println(map2)
    delete(map2,"Go")
    fmt.Println(map2)

    //6. Modify data
    fmt.Println(map2)
    map2["Python"] = 95
    fmt.Println(map2)
    map2["Python"] = 100
    fmt.Println(map2)

    / / 7. Length
    fmt.Println(len(map2))

}
Copy the code