开发者学堂课程【Go 语言核心编程 - 基础语法、数组、切片、Map: map 的遍历】学习笔记,与课程紧密联系,让用户快速学习知识。
课程地址:https://developer.aliyun.com/learning/course/625/detail/9659
map 的遍历
目录:
一、map 遍历
二、map 的长度
一、map 遍历:
案例演示相对复杂的 map 遍历:该 map 的 value 又是一个 map 说明: map 的遍历使用 for-range 的结构遍历
Map 的遍历不能用简单的 for 循环,因为 for 循环在遍历的时候要拿到数组的下标,但是 map 的 key 不是数字也不一定是 123 这样的数字可能不是连续的有可能是字符串,所以在 map 遍历时只能用 for-range。
案例:
package main
import (
"fmt”
)
func main() {
//使用 for-range 遍历 map
//第二种方式
cities := make(map[string]string)
cities[ "no1"]=“北京"
cities[ "no2"]=“天津”
cities["no3"]=“上海”"
for k, v := range cities {
(分别把他们的每一个key value遍历出来)
fmt.Printf("k=%v v=%v\n", k,v)
}
}
因为下标,这里不能用 for 循环。
//使用 for-range 遍历一个结构比较复杂的 map
studentMap := make(map[string]map[string]string)
(这里较为复杂的原因因为他的值也是一个 map,意味着如果要遍历说明要 for range 两次)
studentMap[ "stu01"] =make(map[string]string3)
studentMap[ "stu01"]["name"] =“tom"
studentMap[ "stu01"]["sex"]=“男”
studentMap[ "stu01"]["address"]="北京长安街~”
studentMap[ "stu02"] =make(map[string]string,3)//这句话不能少!!
studentMap[ "stu02"][ "name"] ="mary"
studentMap[ "stu02"]["sex"]=“女”
studentMap[ "stu02"][ "address"]=“上海黄浦江~"
for k1, v1 := range studentMap {
(这里遍历后,k1 就是 student01 和 02 这样一个值,v1 又是一个 map)
fmt.Println( "k1=", k1)
for k2, v2 := range v1 {
(这里就是一个值)
fmt.Printf("\t k2=%v v2=%v\n", k2,v2)
}
fmt.Print1n(
}
输出后发现 k1 是 student01 对应一个 map 里面有三对,有地址名字性别, student02 也是对应一个 map,在增加也是这样遍历,这样就演示了一个双层 for range 的遍历。
二、map 的长度
Func len:
(统计一个 map 有多少对 key value)
func len( Type) int
内建函数 len 返回 v 的长度,这取决于具体类型:
数组: v 中元素的数量
数组指针:“ v 中元素的数量( v 为 nil 时 panic )
切片、映射: v 中元素的数量:若 v 为 nil. len(v) 即为零
字符串: v 中字节的数量
通道:通道缓存中队列(未读取)元素的数量:若 v 为 nil,len(v) 即为零
案例:
}
fmt.Print1n( "cities 有",len(cities),”对key-value")
这里可以统计出有多少对 key value
案例演示: fmt.Println(len(stus))
尤其注意在进行遍历时用 for range 而不是 for 循环,因为 map 的 k 不一定是数字或连续的数字。