Go 语言 中 sync.Map 的删除元素是使用内置的 Delete 函数。
func (m *Map) Delete(key interface{})
参数 | 描述 |
---|---|
m | sync.Map 对象。 |
key | 需要删除的键。 |
从 sync.Map 中删除键为 key 的元素。
使用 sync.Map Delete 删除元素
package main
import (
"fmt"
"sync"
)
func main() {
fmt.Println("嗨客网(www.haicoder.net)")
//使用 sync.Map Delete 删除元素
var mapHaiCoder sync.Map
mapHaiCoder.Store("Server", "Golang")
mapHaiCoder.Store("JavaScript", "Vue")
mapHaiCoder.Store("Db", "Redis")
fmt.Println(mapHaiCoder.Load("Server"))
mapHaiCoder.Delete("Server")
fmt.Println(mapHaiCoder.Load("Server"))
}
程序运行后,控制台输出如下:
我们创建了一个 sync.Map,创建完之后,使用 Store 存储元素,接着,我们使用 Load 成功获取了元素,再次使用 Delete 将 KEY 为 “Server” 的元素删除,最后再获取 KEY 为 “Server” 的元素已经不存在了 。
使用 sync.Map Delete 删除不存在的元素,不会报错
package main
import (
"fmt"
"sync"
)
func main() {
fmt.Println("嗨客网(www.haicoder.net)")
//使用 sync.Map Delete 删除不存在的元素,不会报错
var mapHaiCoder sync.Map
mapHaiCoder.Store("Server", "Golang")
mapHaiCoder.Store("JavaScript", "Vue")
mapHaiCoder.Store("Db", "Redis")
mapHaiCoder.Delete("Server")
mapHaiCoder.Delete("Server")
fmt.Println("Delete Ok")
}
程序运行后,控制台输出如下:
两次从 sync.Map 中删除了同一个 KEY 的元素,并没有报错,而且程序正常运行结束,说明删除不存在的 KEY,程序不会有任何异常。
Go 语言中 sync.Map 的删除元素是使用内置的 Delete 函数。Go 语言 sync.Map Delete 语法:
func (m *Map) Delete(key interface{})