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"] = 100scoreMap["English"] = 200scoreMap["Chinese"] = 150//遍历for key, value := range scoreMap {fmt.Println("key:", key, "value:", value)}//删除delete(scoreMap, "Math")//修改scoreMap["English"] = 100fmt.Println("-------------")//遍历for key, value := range scoreMap {fmt.Println("key:", key, "value:", value)}