go map学习笔记
程序员文章站
2024-02-15 19:34:34
...
go map note
1.声明和赋值
var myGreeting map[string]string //声明map,可以直接make()
myGreeting = make(map[string]string) //声明后必须make才能赋值!!
var myGreeting = make(map[string]string) //直接make()的方式
myGreeting := make(map[string]string) //更简短的创建方式
myGreeting := map[string]string{ //声明同时赋值的方式
"Tim": "Good morning!",
"Jenny": "Bonjour!",
}
myGreeting["Tim"] = "Good morning."
myGreeting["Jenny"] = "Bonjour."
2.修改删除等操作
myGreeting["Harleen"] = "Howdy"
delete(myGreeting, "two")
val, exists := myGreeting[2] //返回值和是否存在的bool值
3.遍历方法
for key, val := range myGreeting {
fmt.Println(key, " - ", val)
}