map初始化的四种方法
var myGreeting map[string]string
fmt.Println(myGreeting)// map[]
fmt.Println(myGreeting == nil) //truemyGreeting2 := make(map[string]string)
myGreeting2["Tim"] = "Good morning."
myGreeting2["Jenny"] = "Bonjour."fmt.Println(myGreeting2)//map[Jenny:Bonjour. Tim:Good morning.]myGreeting3 := map[string]string{}
myGreeting3["Tim"] = "Good morning."
myGreeting3["Jenny"] = "Bonjour."
fmt.Println(myGreeting3)//map[Jenny:Bonjour. Tim:Good morning.]myGreeting4 := map[string]string{
"Time":"Good morning.",
"Jenny": "Bonjour.",
}fmt.Println(myGreeting4)//map[Jenny:Bonjour. Time:Good morning.]
fmt.Println(myGreeting4["Jenny"]) //Bonjour.
map添加操作
myGreeting := map[string]string{
"Tim":"Good morning!",
"Jenny": "Bonjour!",
}myGreeting["Harleen"] = "Howdy"fmt.Println(myGreeting)
len 获取map的长度
myGreeting := map[string]string{
"Tim":"Good morning!",
"Jenny": "Bonjour!",
}myGreeting["Harleen"] = "Howdy"fmt.Println(len(myGreeting))
更新map
myGreeting := map[string]string{
"Tim":"Good morning!",
"Jenny": "Bonjour!",
}myGreeting["Harleen"] = "Howdy"
fmt.Println(myGreeting)
myGreeting["Harleen"] = "Gidday"
fmt.Println(myGreeting)
删除map的值:
myGreeting := map[string]string{
"zero":"Good morning!",
"one":"Bonjour!",
"two":"Buenos dias!",
"three": "Bongiorno!",
}fmt.Println(myGreeting)
delete(myGreeting, "two")
fmt.Println(myGreeting)
// ------------------------------------------------------------
myGreeting := map[int]string{
0: "Good morning!",
1: "Bonjour!",
2: "Buenos dias!",
3: "Bongiorno!",
}fmt.Println(myGreeting)
delete(myGreeting, 7)
fmt.Println(myGreeting)
判断key是否存在
myGreeting := map[int]string{
0: "Good morning!",
1: "Bonjour!",
2: "Buenos dias!",
3: "Bongiorno!",
}fmt.Println(myGreeting)// delete(myGreeting, 2)if val, exists := myGreeting[2];
exists {
fmt.Println("That value exists.")
fmt.Println("val: ", val)
fmt.Println("exists: ", exists)
} else {
fmt.Println("That value doesn't exist.")
fmt.Println("val: ", val)
fmt.Println("exists: ", exists)
}fmt.Println(myGreeting)
scoreMap := make(map[string]int)
scoreMap["张三"] = 90
scoreMap["小明"] = 100
// 如果key存在ok为true,v为对应的值;不存在ok为false,v为值类型的零值
v, ok := scoreMap["张三"]
if ok {
fmt.Println(v)
} else {
fmt.Println("查无此人")
}
map的遍历
myGreeting := map[int]string{
0: "Good morning!",
1: "Bonjour!",
2: "Buenos dias!",
3: "Bongiorno!",
}for key, val := range myGreeting {
fmt.Println(key, " - ", val)
}
}
scoreMap := make(map[string]int)
scoreMap["张三"] = 90
scoreMap["小明"] = 100
scoreMap["王五"] = 60
for k := range scoreMap {
fmt.Println(k)
}
推荐阅读
- 【golang】leetcode中级-字母异位词分组&无重复字符的最长子串
- 彻底理解Golang Map
- kratos线上开源年会它来啦~
- 深入浅出 Golang 资源嵌入方案(go-bindata篇)
- 深入浅出 Golang 资源嵌入方案(前篇)
- golang 经典案例总结
- Go实战 | 基于有向无环图的并发执行流的实现
- Golang 数组和切片
- Go JSON编码与解码()