studentMap := make(map[string]map[string]string)
fmt.Printf("studentMap 类型: %T, 值: %v \n", studentMap, studentMap)
studentMap["01"] = make(map[string]string)
studentMap["01"]["name"] = "xiao"
studentMap["01"]["sex"] = "男"
studentMap["02"] = make(map[string]string)
studentMap["02"]["name"] = "xiao"
studentMap["02"]["sex"] = "男"
studentMap["02"]["addr"] = "上海"
fmt.Println("studentMap = ", studentMap)
// studentMap = map[01:map[name:xiao sex:男] 02:map[addr:上海 name:xiao sex:男]]
增加、修改
map[key] = value // 不存在key就是新增,存在就是修改
删除
func delete(m map[Type]Type1, key Type)
内建函数delete按照指定的键将元素从映射中删除。若m为nil或无此元素,delete不进行操作。
// 删除 studentMap["02"]["addr"]
delete(studentMap["02"], "addr")
fmt.Printf("studentMap[02] = %v \n", studentMap["02"])
// studentMap[02] = map[name:xiao sex:男]
var bookMap map[string]string = map[string]string{
"01": "Golang",
"02": "GoWeb",
}
fmt.Println("bookMap = ", bookMap)
bookMap = make(map[string]string) // bookMap = map[01:Golang 02:GoWeb]
fmt.Println("bookMap = ", bookMap) // bookMap = map[]
- 只可以一个一个的删除,
- 可以遍历所有的key,逐个删除
- 重新赋值 map = make(…) make一个新的,让原来的成为垃圾,被gc回收
查找
// 查找
val, ok := bookMap["03"]
// 返回两个值,一个是key对应的value, 另一个是否有这个key
if ok {
fmt.Printf("存在bookMap[01], 值为: %v \n", val)
} else {
fmt.Println("不存在bookMap[01]")
}
遍历map
for range 遍历map,获取到的值就是 key, value
单层map遍历
// for range 遍历map
var bookMap01 map[string]string = map[string]string{
"01": "Golang",
"02": "GoWeb",
}
for k, v := range bookMap01 {
fmt.Printf("k = %v, v= %v \n", k, v)
}
// k = 01, v= Golang
// k = 02, v= GoWeb
双层map遍历
studentMap := make(map[string]map[string]string)
fmt.Printf("studentMap 类型: %T, 值: %v \n", studentMap, studentMap)
studentMap["01"] = make(map[string]string)
studentMap["01"]["name"] = "xiao"
studentMap["01"]["sex"] = "男"
studentMap["02"] = make(map[string]string)
studentMap["02"]["name"] = "xiao"
studentMap["02"]["sex"] = "男"
studentMap["02"]["addr"] = "上海"
fmt.Println("studentMap = ", studentMap)
for k1, v1 := range studentMap {
fmt.Println("k1 = ", k1)
for k2, v2 := range v1 {
fmt.Printf("\t%v[%v] = %v \n", k1, k2, v2)
}
fmt.Println()
}
// 输出
k1 = 01
01[name] = xiao
01[sex] = 男
k1 = 02
02[name] = xiao
02[sex] = 男
map的长度
func len(v Type) int
内建函数len返回 v 的长度,这取决于具体类型:
- 数组:v中元素的数量
- 数组指针:*v中元素的数量(v为nil时panic)
- 切片、映射:v中元素的数量;若v为nil,len(v)即为零
- 字符串:v中字节的数量
- 通道:通道缓存中队列(未读取)元素的数量;若v为 nil,len(v)即为零