A preliminary understanding of map based on Go language

map of Go language foundation

The hash relation in the container is used to implement the hash relation.

map

map is an unordered key value based data structure. map in Go language is a reference type and must be initialized before it can be used.

map definition

The definition syntax of map in Go language is as follows:

map[KeyType]ValueType

Among them,

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

The default initial value of a map type variable is nil, so you need to use the make() function to allocate memory. The syntax is:

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 usage

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

func main() {
	// map[Key]Value
	var a = make(map[string]int, 8)
	a["Zhang San"] = 90
	a["Li Si"] = 100
	fmt.Println(a)
	fmt.Println(a["Li Si"])
	fmt.Printf("type of a:%T\n", a)
}

Output:

map[Zhang San:90 Li Si:100]
100
type of a:map[string]int

map also supports filling in elements when declaring, for example:

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

Output:

map[password:123456 username:luozongwei]

The output is sorted according to the dictionary set from small to large

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["Xiao Ming"] = 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("No one was found")
	}
}

Traversal of map

Go language uses for range to traverse map.

func main() {
	scoreMap := make(map[string]int)
	scoreMap["Zhang San"] = 90
	scoreMap["Xiao Ming"] = 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["Xiao Ming"] = 100
	scoreMap["Naza"] = 60
	for k := range scoreMap {
		fmt.Println(k)
	}
}

Note: the order of elements when traversing the map is related to the order in which key value pairs are added.

Use the delete() function to delete key value pairs

Use the delete() built-in function to delete a set of key value pairs from the map. The format of the delete() function is as follows:

delete(map, key)

Among them,

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

The example code is as follows:

func main() {
	scoreMap := make(map[string]int)
	scoreMap["Zhang San"] = 90
	scoreMap["Naza"] = 60
	scoreMap["Xiao Ming"] = 100
	// Before deletion
	for k := range scoreMap {
		fmt.Println(k)
	}
	fmt.Println()
	// After deletion
	delete(scoreMap, "Xiao Ming")
	for k := range scoreMap {
		fmt.Println(k)
	}
}
Xiao Ming
 Zhang San
 Naza

Zhang San
 Naza

Traverse the map in the specified order

package main

import (
	"fmt"
	"math/rand"
	"sort"
	"time"
)

func main() {
	rand.Seed(time.Now().UnixNano())         // Initialize random number seed
	var scoreMap = make(map[string]int, 200) // 200 refers to the capacity of the map. It is best to add the capacity when initializing the map
	for i := 0; i < 100; i++ {
		key := fmt.Sprintf("stu%02d", i) // Generate string starting with stu
		value := rand.Intn(100)         // Generate random numbers from 0 to 99
		scoreMap[key] = value
	}
	//Take out all the keys in the map and save them into 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])
	}
}

Output:

stu00 59
stu01 48
stu02 87
stu03 75
stu04 92
stu05 86
stu06 40
stu07 37
stu08 27
stu09 68
stu10 70
... Most of the answers are omitted 

Slice (array) with element of map type

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

func main() {
	var map_slice = make([]map[string]string, 3)
	for index, value := range map_slice {
		fmt.Printf("index:%d value:%v\n", index, value)
	}
	fmt.Println("after init")
	// Initialize the map element in the slice
	map_slice[0] = make(map[string]string, 10)
	map_slice[0]["name"] = "xiaoluo"
	map_slice[0]["password"] = "12345"
	map_slice[0]["address"] = "hezhou"
	for index, value := range map_slice {
		fmt.Printf("index:%d value:%v\n", index, value)
	}
}

Output:

index:0 value:map[]
index:1 value:map[]
index:2 value:map[]
after init
index:0 value:map[address:hezhou name:xiaoluo password:12345]
index:1 value:map[]
index:2 value:map[]

In fact, the so-called slicing means all or part of an array. There is no essential difference between the two. It is similar to slicing in other languages, but go language gives slicing more concepts and usage

map with value of slice type

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

func main() {
	var slice_map = make(map[string][]string, 3)
	fmt.Println(slice_map)
	fmt.Println("after init")
	key := "China"
	value, ok := slice_map[key]
	if !ok {
		value = make([]string, 0, 2)
	}
	value = append(value, "beijing", "shanghai")
	slice_map[key] = value
	fmt.Println(slice_map)
}

Output:

map[]
after init
map[China:[beijing shanghai]]

Exercises

  1. Write a program to count the number of occurrences of each word in a string. For example, in "how do you do", how = 1, do = 2, you = 1.
package main

import (
	"fmt"
	"strings"
)

func main() {
	// Split string into slices
	str := "how do you do"
	str_slice := strings.Split(str, " ")

	// Process the segmented slices
	var score_map = make(map[string]int, 10)
	for _, value := range str_slice {
		score_map[value]++
	}
	fmt.Println(score_map)
}
  1. Observe the following code and write the final print result.
func main() {
	type Map map[string][]int
    m := make(Map)     // (1)
    s := []int{1, 2}   // (2)
    s = append(s, 3)   // (3)
	fmt.Printf("%+v\n", s)
    m["q1mi"] = s	   // (4)
    s = append(s[:1], s[2:]...) // (5)
	fmt.Printf("%+v\n", s)
	fmt.Printf("%+v\n", m["q1mi"])
}
[1 2 3]
[1 3]  
[1 3 3]
Here are the answers[1,3,3]To parse:
appear[1,3,3]The main reason is slice The bottom layer of is an array, different slice May share the same bottom layer.
That is, assumptions m At the beginning, the bottom is[ , , ]Three positions
 When (2)After processing, the bottom layer becomes[1,2, ](Because at this time, it is assumed that the bottom layer is different slice Shared,s and m Shared)
(3) Later become [1,2,3]
(4) Can be understood as m It also points to the same bottom layer, that is[1,2,3]
(5) take s And the bottom became s:[1,3] And the bottom[1,3,3]
Final output m It becomes[1,3,3]

Keywords: Go Back-end

Added by sgaron on Wed, 16 Feb 2022 09:56:58 +0200