map声明的方式
//声明
var m map[string]string
//在使用map之前,先make,make的作用就是给map分配空间
m = make(map[string]string)
m["lover"] = "Yzx"
m["friend1"] = "Zxw"
m["friend2"] = "Zzc"
fmt.Println(m) //map[friend1:Zxw friend2:Zzc lover:Yzx]
//第二种声明方式
m2 := make(map[string]string, 10)
m2["Math"] = "100"
m2["English"] = "200"
m2["Chinese"] = "150"
fmt.Println(m2) //map[Chinese:150 English:200 Math:100]
//第三种声明方式
m3 := map[string]int{
"Math": 50,
"Chinese": 80,
"English": 90,
}
结果如下:
map的使用
scoreMap := make(map[string]int)
scoreMap["Math"] = 100
scoreMap["English"] = 200
scoreMap["Chinese"] = 150
//遍历
for key, value := range scoreMap {
fmt.Println("key:", key, "value:", value)
}
//删除
delete(scoreMap, "Math")
//修改
scoreMap["English"] = 100
fmt.Println("-------------")
//遍历
for key, value := range scoreMap {
fmt.Println("key:", key, "value:", value)
}