- map的声明方式有以下三种。
package mainimport "fmt"func main() {//第一种声明方式//声明map1是一个map类型,key是String,value是Stringvar myMap1 map[string] stringif myMap1 == nil {fmt.Println("myMap1 是一个空map")}//在使用map前,需要先用make给map分配数据空间myMap1 = make(map[string]string,10)myMap1["one"] = "java"myMap1["two"] = "c"myMap1["three"] = "python"fmt.Println("第一种方式", myMap1)//第二种声明方式myMap2 := make(map[int]string)myMap2[1] = "navy"myMap2[2] = "hj"myMap2[3] = "liu"fmt.Println("第二种方式", myMap2)//第三种声明方式myMap3 := map[string] string{"one": "php","two": "c++","three": "python",}fmt.Println("第三种方式", myMap3)
}
- map的使用方式
map的增删改查
package mainimport "fmt"func main() {cityMap :=make(map[string]string)//添加cityMap["China"] = "Beijing"cityMap["Japan"] = "Tokyo"cityMap["USA"] = "NewYork"//遍历for key,value := range cityMap {fmt.Println("key = ",key)fmt.Println("value = ",value)}//删除delete(cityMap,"Japan")//修改cityMap["USA"] = "DC"fmt.Println("-------------")//遍历for key, value := range cityMap {fmt.Println("key = ",key)fmt.Println("value = ",value)}
}
- map的传参
package mainimport ("fmt"
)func printMap(cityMap map[string]string) {//cityMap 是一个引用传递for key, value := range cityMap{fmt.Println("key = ",key)fmt.Println("value = ",value)}
}func changeValue(cityMap map[string] string) {cityMap["England"] = "Lodndon"
}func main() {cityMap := make(map[string]string)//添加cityMap["China"] = "Beijing"cityMap["Japan"] = "Tokyo"cityMap["USA"] = "NewYork"//遍历printMap(cityMap)//增加一个mapchangeValue(cityMap)fmt.Println("---------------")//遍历printMap(cityMap)}