1.map声明变量的方式
//map的声明方式
func main() {
//第一种
var myMap1 map[string]string
if myMap1==nil{
fmt.Println("map为空")
}
myMap1=make(map[string]string,10)
myMap1["one"]="xiaoming"
myMap1["two"]="xiaohong"
myMap1["three"]="xiaoli"
fmt.Println(myMap1)
//第二种
myMap2:=make(map[int]string)
myMap2[1]="xiaoming"
myMap2[2]="xiaohong"
myMap2[3]="xiaoli"
fmt.Println(myMap2)
//第三种
myMap3:=map[string]string{
"one":"xiaoming",
"two":"xiaoli",
"three":"xiaohong",
}
fmt.Println(myMap3)
}
2.map的使用方式
//遍历输出函数
func PrintMap(map1 map[int]string) {
//map1是引用传递,传递过来的是指针
for key,vaule:=range map1{
fmt.Println("key=",key)
fmt.Println("value=",vaule)
}
}
//数值修改函数
func ChangeMap(map1 map[int]string) {
map1[2]="hhh"
}
func main() {
map1:=make(map[int]string)
//添加
map1[1]="hello"
map1[2]="hi"
map1[3]="he"
//遍历
for key,vaule:=range map1{
fmt.Println("key=",key)
fmt.Println("value=",vaule)
}
//删除
delete(map1,1)
//修改
map1[3]="haha"
ChangeMap(map1)
fmt.Println("=============")
//遍历
PrintMap(map1)
}