- map的声明方式有以下三种。
go
package main
import "fmt"
func main() {
//第一种声明方式
//声明map1是一个map类型,key是String,value是String
var myMap1 map[string] string
if 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的增删改查
go
package main
import "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的传参
go
package main
import (
"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)
//增加一个map
changeValue(cityMap)
fmt.Println("---------------")
//遍历
printMap(cityMap)
}