mirror of
https://github.com/unknwon/the-way-to-go_ZH_CN.git
synced 2025-08-12 00:11:36 +08:00
8.1
This commit is contained in:
@@ -1,4 +1,7 @@
|
||||
#8.2 删除元素
|
||||
# 8.2 测试键值对是否存在及删除元素
|
||||
|
||||
188
|
||||
|
||||
测试map1中是否存在key1:
|
||||
|
||||
在例子8.1中,我们已经见过可以使用val1 = map1[key1]的方法获取key1对应的值val1。如果map中不存在key1,val1就是一个值类型的空值。
|
||||
@@ -29,11 +32,11 @@ isPresent返回一个bool值:如果key1存在于map1,val1就是key1对应的
|
||||
|
||||
package main
|
||||
import "fmt"
|
||||
|
||||
|
||||
func main() {
|
||||
var value int
|
||||
var isPresent bool
|
||||
|
||||
|
||||
map1 := make(map[string]int)
|
||||
map1["New Delhi"] = 55
|
||||
map1["Beijing"] = 20
|
||||
@@ -44,11 +47,11 @@ isPresent返回一个bool值:如果key1存在于map1,val1就是key1对应的
|
||||
} 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"]
|
||||
|
Reference in New Issue
Block a user