Files
the-way-to-go_ZH_CN/eBook/08.2.md
Unknwon 19b7cd9899 8.1
2015-02-20 18:19:22 -05:00

76 lines
2.1 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 8.2 测试键值对是否存在及删除元素
188
测试map1中是否存在key1
在例子8.1中我们已经见过可以使用val1 = map1[key1]的方法获取key1对应的值val1。如果map中不存在key1val1就是一个值类型的空值。
这就会给我们带来困惑了现在我们没法区分到底是key1不存在还是它对应的value就是空值。
为了解决这个问题,我们可以这么用: val1, isPresent = map1[key1]
isPresent返回一个bool值如果key1存在于map1val1就是key1对应的value值并且isPresent为true如果key1不存在val1就是一个空值并且isPresent会返回false。
如果你只是想判断某个key是否存在而不关心它对应的值到底是多少你可以这么做
_, ok := map1[key1] // 如果key1存在则ok == true否在ok为false
或者和if混合使用
if _, ok := map1[key1]; ok {
// ...
}
从map1中删除key1
直接: delete(map1, key1)
如果key1不存在该操作不会产生错误。
示例 8.4 [map_testelement.go](examples/chapter_8/map_testelement.go)
package main
import "fmt"
func main() {
var value int
var isPresent bool
map1 := make(map[string]int)
map1["New Delhi"] = 55
map1["Beijing"] = 20
map1["Washington"] = 25
value, isPresent = map1["Beijing"]
if isPresent {
fmt.Printf("The value of \"Beijin\" in map1 is: %d\n", value)
} else {
fmt.Printf("map1 does not contain Beijing")
}
value, isPresent = map1["Paris"]
fmt.Printf("Is \"Paris\" in map1 ?: %t\n", isPresent)
fmt.Printf("Value is: %d\n", value)
// delete an item:
delete(map1, "Washington")
value, isPresent = map1["Washington"]
if isPresent {
fmt.Printf("The value of \"Washington\" in map1 is: %d\n", value)
} else {
fmt.Println("map1 does not contain Washington")
}
}
输出结果:
The value of "Beijing" in map1 is: 20
Is "Paris" in map1 ?: false
Value is: 0
map1 does not contain Washington
##链接
- [目录](directory.md)
- 上一节:[声明,初始化和make](08.1.md)
- 下一节:[for循环构造方法](08.3.md)