go语言——map
创建map
var map1 map[int]string
var map2 = make(map[int]string)
var map3 = map[string]int{"go":89,"python":90}
if map1 == nil{
map1 = make(map[int]string)
fmt.Println()
}
- 默认值:nil,相当于空
- nil的map,不能直接使用
map的使用
var map1 map[int]string
map1 = make(map[int]string)
// 根据key获得对应的value值,如果key存在,返回数值,不存在,获得value的零值
va1ue,ok = map1[4]
if ok {
fmt.Println(value)
} else {
fmt.Println("key不存在,获得零值")
}
//修改数据
fmt.Println(map1)
map1[1] = "agdgdglkadfk"
fmt.Println(map1)
//删除数据,key不存在则不影响
delete(map1,key:3)
fmt.Println(map1)
delete(map1,key:30)
fmt.Println(map1)
map的遍历
map1 := make(map[int]string)
map1[1] = "taincai"
map1[2] = "wudi"
map1[3] = "dsaffsda"
for k,v := range map1 {
fmt.Println(k,v)
}
map与slice
var map1 = map[string]string{"小明":"sdfsdf"}
var map2 = map[string]string{"小明":"sdfsdfsdfsdf"}
var map3 = map[string]string{"小明":"sdfs5632df"}
s1 := make([]map[string]string,0,3)
s1 = append(s1,map1)
s1 = append(s1,map2)
s1 = append(s1,map3)
for _,val := range s1 {
fmt.Printf("小明:%s
",val["小明"])
}