In Go, map is also a container for mapping relations. Different from c++, c++ is implemented by binary trees, while Go is implemented by hash tables.

1. The map definition

map[keyType]valueType
// Define a map of key type int and value type string
var m = map[int]string
Copy the code
  • KeyType: indicates the key type
  • ValueType: indicates the type of a value

2. Use the make function to initialize the map

** Note: the difference between ** and Slice initialization is that size is not required and cap capacity is not required, but it is a good idea to estimate the required capacity to avoid wasting large amounts of memory during subsequent dynamic expansion.

make(map[keyType]valueType, [cap])
// Initialize a map with capacity 10
m = make(map[int]string.10)
Copy the code

3. Add map elements

(1) Added at declaration time

package  main
import "fmt"
//map
 
func main(a){
	m1 := map[string]int{
		"Green Meadow":7."I am the strongest.":3,
	}
	m1["Blue sky and white Clouds"] = 4
	m1["One more."] = 4

	fmt.Println(m1)
}
Copy the code

Output result:

map[I am the strongest:3Blue sky and white clouds:4One more:4Green grassland:7]
Copy the code

(2) First declare, then add

package  main
import "fmt"
//map
 
func main(a){
	var m1 map[string] int
	fmt.Println(m1 == nil)// Return true, reference type, no initialization
	m1 = make(map[string]int.10)
	m1["Blue sky and white Clouds"] = 4
	m1["One more."] = 4

	fmt.Println(m1)
}
Copy the code

Output result:

True map[Blue sky :4 and a :4]Copy the code

(3) Matters needing attention

  • Do not add the same key when adding:

Go is the same as c++, the key value is not repeated, the same key value, after the preceding value

package  main
import "fmt"
//map
 
func main(a){
	var m1 map[string] int
	fmt.Println(m1 == nil)// Return true, reference type, no initialization
	m1 = make(map[string]int.10)
	m1["Blue sky and white Clouds"] = 4
	m1["One more."] = 4
	m1["Blue sky and white Clouds"] = 7// as in c++, the same key value is not repeated
	
  fmt.Println(m1)
}
Copy the code

Output result:

True map[Blue sky :7 and a :4]Copy the code