Go (seven) language basic map

Table of contents

map

1.1 map definition

1.2map basic use

1.3 Determine whether a key exists

1.4 Map traversal

1.5 Use the delete() function to delete key-value pairs

1.6 Traverse the map in the specified order

1.7 The element is a slice of map type

1.8 A map whose value is a slice type


The mapping relationship container provided in the Go language is implemented mapinternally 散列表(hash).

map

        The map is an unordered key-valuedata structure based on the data structure. The map in the Go language is a reference type and must be initialized before it can be used.

1.1 map definition

The definition syntax in Go language  mapis as follows:

map[KeyType]ValueType

in:

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

The default initial value of a variable of the map type is nil, and the make() function needs to be used to allocate memory . The syntax is:

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

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

1.2map basic use

The data in the map appear in pairs. The basic usage sample code of the map is as follows:

func main() {
	scoreMap := make(map[string]int, 8)
	scoreMap["张三"] = 90
	scoreMap["小明"] = 100
	fmt.Println(scoreMap)
	fmt.Println(scoreMap["小明"])
	fmt.Printf("type of a:%T\n", scoreMap)
}

output:

map[小明:100 张三:90]
100
type of a:map[string]int

map also supports filling elements when declaring, for example:

func main() {
	userInfo := map[string]string{
		"username": "沙河小王子",
		"password": "123456",
	}
	fmt.Println(userInfo) //
}

1.3 Determine whether a key exists

        In the Go language, there is a special way of judging whether a key exists in a map. The format is as follows:

value, ok := map[key]
// 如果key存在ok为true,v为对应的值;不存在ok为false,v为值类型的零值

for example:

func main() {
	scoreMap := make(map[string]int)
	scoreMap["张三"] = 90
	scoreMap["小明"] = 100
	// 如果key存在ok为true,v为对应的值;不存在ok为false,v为值类型的零值
	v, ok := scoreMap["张三"]
	if ok {
		fmt.Println(v)
	} else {
		fmt.Println("查无此人")
	}
}

1.4 Map traversal

for rangeTraversal map is used in Go language .

func main() {
	scoreMap := make(map[string]int)
	scoreMap["张三"] = 90
	scoreMap["小明"] = 100
	scoreMap["娜扎"] = 60
	for k, v := range scoreMap {
		fmt.Println(k, v)
	}
}


张三 90
小明 100
娜扎 60

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

func main() {
	scoreMap := make(map[string]int)
	scoreMap["张三"] = 90
	scoreMap["小明"] = 100
	scoreMap["娜扎"] = 60
	for k := range scoreMap {
		fmt.Println(k)
	}
}
张三
小明
娜扎

Note:  The order of elements when traversing the map has nothing to do with the order in which key-value pairs are added. map is unordered

1.5 Use the delete() function to delete key-value pairs

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

delete(map, key)

in,

  • map: Indicates that the map of the key-value pair is to be deleted
  • key: the key representing the key-value pair to be deleted

The sample code is as follows:

func main(){
	scoreMap := make(map[string]int)
	scoreMap["张三"] = 90
	scoreMap["小明"] = 100
	scoreMap["娜扎"] = 60
	delete(scoreMap, "小明")//将小明:100从map中删除
	for k,v := range scoreMap{
		fmt.Println(k, v)
	}
}

张三 90
娜扎 60

1.6 Traverse the map in the specified order

func main() {
	rand.Seed(time.Now().UnixNano()) //初始化随机数种子

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

	for i := 0; i < 100; i++ {
		key := fmt.Sprintf("stu%02d", i) //生成stu开头的字符串
		value := rand.Intn(100)          //生成0~99的随机整数
		scoreMap[key] = value
	}
	//取出map中的所有key存入切片keys
	var keys = make([]string, 0, 200)
	for key := range scoreMap {
		keys = append(keys, key)
	}
	//对切片进行排序
	sort.Strings(keys)
	//按照排序后的key遍历map
	for _, key := range keys {
		fmt.Println(key, scoreMap[key])
	}
}

1.7 The element is a slice of map type

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

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")
	// 对切片中的map元素进行初始化
	mapSlice[0] = make(map[string]string, 10)
	mapSlice[0]["name"] = "小王子"
	mapSlice[0]["password"] = "123456"
	mapSlice[0]["address"] = "沙河"
	for index, value := range mapSlice {
		fmt.Printf("index:%d value:%v\n", index, value)
	}
}

1.8 A map whose value is a slice type

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

func main() {
	var sliceMap = make(map[string][]string, 3)
	fmt.Println(sliceMap)
	fmt.Println("after init")
	key := "中国"
	value, ok := sliceMap[key]
	if !ok {
		value = make([]string, 0, 2)
	}
	value = append(value, "北京", "上海")
	sliceMap[key] = value
	fmt.Println(sliceMap)
}

Guess you like

Origin blog.csdn.net/qq_54729417/article/details/127854765