要从Map中删除一个键,我们可以使用Go的内置 删除 函数。需要注意的是,当我们从Map中删除一个键时,它的值也会被删除,因为在Go中,键值对就像一个单一的实体。
语法
删除函数的语法如下所示。
delete(map,key)
一旦我们以上述格式调用该函数,那么Map中的键就会被删除。
现在,让我们在Go代码中使用上述函数,了解它是如何工作的。
例子1
考虑一下下面的代码
package main
import (
"fmt"
)
func main() {
m := make(map[string]int)
m["mukul"] = 10
m["mayank"] = 9
m["deepak"] = 8
fmt.Println(m)
fmt.Println("Deleting the key named deepak from the map")
delete(m, "deepak")
fmt.Println(m)
}
在上面的代码中,我们有一个名为m的Map,其中包含一些字符串作为键,一些整数值是这些键的值。后来,我们利用delete()函数从Map中删除了名为 “deepak “的键,然后我们再次打印Map的内容。
如果我们用命令go run main.go来运行上述代码,我们将在终端得到以下输出。
输出
map[mukul:10 mayank:9 deepak:8]
Deleting the key named deepak from the map
map[mukul:10 mayank:9]
上面的代码在大多数例子中都能正常工作,但在一种情况下会引起恐慌。引起恐慌的情况是我们不确定某个键是否存在于Map中。
例二
为了确保我们不会写出引起恐慌的代码,我们可以使用下面的代码。
package main
import (
"fmt"
)
func main() {
m := make(map[string]int)
m["mukul"] = 10
m["mayank"] = 9
m["deepak"] = 8
fmt.Println(m)
fmt.Println("Deleting the key named deepak from the map")
if _, ok := m["deepak"]; ok {
delete(m, "deepak")
}
fmt.Println(m)
}
上述方法更加安全,建议采用第一种方法。
输出
如果我们用命令 go run main.go 来运行上述代码,我们将在终端得到以下输出。
map[mukul:10 mayank:9 deepak:8]
Deleting the key named deepak from the map
map[mukul:10 mayank:9]