Files
the-way-to-go_ZH_CN/eBook/08.2.md
Haigang Zhou 30ca13a369 7-8 章修改 (#842)
Co-authored-by: Joe Chen <jc@unknwon.io>
2022-05-10 13:53:30 +08:00

81 lines
2.2 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 测试键值对是否存在及删除元素
测试 `map1` 中是否存在 `key1`
在例子 8.1 中,我们已经见过可以使用 `val1 = map1[key1]` 的方法获取 `key1` 对应的值 `val1`。如果 `map` 中不存在 `key1``val1` 就是一个值类型的空值。
这就会给我们带来困惑了:现在我们没法区分到底是 `key1` 不存在还是它对应的 `value` 就是空值。
为了解决这个问题,我们可以这么用:`val1, isPresent = map1[key1]`
`isPresent` 返回一个 `bool` 值:如果 `key1` 存在于 `map1``val1` 就是 `key1` 对应的 `value` 值,并且 `isPresent``true`;如果 `key1` 不存在,`val1` 就是一个空值,并且 `isPresent` 会返回 `false`
如果你只是想判断某个 `key` 是否存在而不关心它对应的值到底是多少,你可以这么做:
```go
_, ok := map1[key1] // 如果key1存在则ok == true否则ok为false
```
或者和 `if` 混合使用:
```go
if _, ok := map1[key1]; ok {
// ...
}
```
`map1` 中删除 `key1`
直接 `delete(map1, key1)` 就可以。
如果 `key1` 不存在,该操作不会产生错误。
示例 8.4 [map_testelement.go](examples/chapter_8/map_testelement.go)
```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 \"Beijing\" 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-range 的配套用法](08.3.md)