Map of go language foundation

Time:2021-5-12

The mapping container provided in go language ismapFor internal useHash table (hash)realization.

Map is an unordered map based onkey-valueMap in go language is a reference type, which must be initialized before it can be used.

Map definition

In go languagemapThe definition syntax of is as follows:

map[KeyType]ValueType

Among them,

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

The default initial value of map type variable is nil, and the make() function is needed to allocate memory. The syntax is as follows:

make(map[KeyType]ValueType, [cap])

Cap represents the capacity of the map. Although this parameter is not necessary, we should specify an appropriate capacity for the map when initializing it.

Map basic use

The data in the map are presented in pairs. The basic use example code of the map is as follows:

func main() {
	scoreMap := make(map[string]int, 8)
	Scoremap ["Zhang San"] = 90
	Scoremap ["Xiaoming"] = 100
	fmt.Println(scoreMap)
	FMT. Println (scoremap ["Xiaoming"])
	fmt.Printf("type of a:%T\n", scoreMap)
}

Output:

Map [Xiaoming: 100 sheets, 3:90]
100
type of a:map[string]int

Map also supports filling elements at declaration time, such as:

func main() {
	userInfo := map[string]string{
		"User name": "Shahe prince,",
		"password": "123456",
	}
	fmt.Println(userInfo) //
}

Determine whether a key exists

In go language, there is a special way to judge whether the key in map exists. The format is as follows:

value, ok := map[key]

for instance:

func main() {
	scoreMap := make(map[string]int)
	Scoremap ["Zhang San"] = 90
	Scoremap ["Xiaoming"] = 100
	//If the key exists, OK is true and V is the corresponding value; There is no zero value with OK as false and V as value type
	v. OK: = scoremap ["Zhang San"]
	if ok {
		fmt.Println(v)
	} else {
		FMT. Println
	}
}

Traversal of map

Use in go languagefor rangeTraverse the map.

func main() {
	scoreMap := make(map[string]int)
	Scoremap ["Zhang San"] = 90
	Scoremap ["Xiaoming"] = 100
	Scoremap ["Naza"] = 60
	for k, v := range scoreMap {
		fmt.Println(k, v)
	}
}

But when we just want to traverse the key, we can write it as follows:

func main() {
	scoreMap := make(map[string]int)
	Scoremap ["Zhang San"] = 90
	Scoremap ["Xiaoming"] = 100
	Scoremap ["Naza"] = 60
	for k := range scoreMap {
		fmt.Println(k)
	}
}

be careful:When traversing the map, the order of elements is independent of the order of adding key value pairs.

Use the delete() function to delete key value pairs

usedelete()The built-in function removes a set of key value pairs from the map,delete()The format of the function is as follows:

delete(map, key)

Among them,

  • Map: the map to delete the key value pair
  • Key: the key of the key value pair to be deleted

The sample code is as follows:

func main(){
	scoreMap := make(map[string]int)
	Scoremap ["Zhang San"] = 90
	Scoremap ["Xiaoming"] = 100
	Scoremap ["Naza"] = 60
	Delete (scoremap, "Xiaoming") // delete Xiaoming: 100 from the map
	for k,v := range scoreMap{
		fmt.Println(k, v)
	}
}

Traverse the map in the specified order

func main() {
	Rand. Seed (time. Now(). Unixnano()) // initialize 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
	}
	//Take out all the keys in the map and store them in the slice keys
	var keys = make([]string, 0, 200)
	for key := range scoreMap {
		keys = append(keys, key)
	}
	//Sort slices
	sort.Strings(keys)
	//Traverse the map according to the sorted key
	for _, key := range keys {
		fmt.Println(key, scoreMap[key])
	}
}

The element is a slice of type map

The following code demonstrates the operation when the element in the slice is of type map:

func main() {
	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] [name] = "Little Prince"
	mapSlice[0]["password"] = "123456"
	Mapslice [0] [address] = "Shahe"
	for index, value := range mapSlice {
		fmt.Printf("index:%d value:%v\n", index, value)
	}
}

Map whose value is slice type

The following code demonstrates the operation of slice type in map:

func main() {
	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)
}

Exercises

  1. Write a program to count the number of times each word appears in a string. For example, in “how do you do”, how = 1, do = 2, you = 1.
  2. Look at the code below and write the final print result.
func main() {
	type Map map[string][]int
	m := make(Map)
	s := []int{1, 2}
	s = append(s, 3)
	fmt.Printf("%+v\n", s)
	m["q1mi"] = s
	s = append(s[:1], s[2:]...)
	fmt.Printf("%+v\n", s)
	fmt.Printf("%+v\n", m["q1mi"])
}