Go 语言 中 sync.Map 的元素遍历,不可以使用 for 循环 或者 for range 循环,而是使用 Range 配合一个回调 函数 进行遍历操作。
通过回调函数返回内部遍历出来的值,Range 参数中回调函数的返回值在需要继续迭代遍历时,返回 true,终止迭代遍历时,返回 false。
func (m *Map) Range(f func(key, value interface{}) bool)
参数 | 描述 |
---|---|
m | sync.Map 对象。 |
f | 遍历到每一个元素的处理函数。 |
key | map 中元素的键。 |
value | map 中元素的值。 |
sync.Map 的元素遍历 Range 函数,接受的参数是一个 匿名函数,该函数接受两个 interface 类型的 参数 ,返回一个 bool 类型的结果。
两个参数,分别对应 sync.Map 的 key 和 value。返回的 bool 结果,如果为 true,表明遍历接受,false,表明遍历继续。
使用 sync.Map Range 遍历元素
package main
import (
"fmt"
"sync"
)
func walk(key, value interface{}) bool {
fmt.Println("Key =", key, "Value =", value)
return true
}
func main() {
fmt.Println("嗨客网(www.haicoder.net)")
//使用 sync.Map Range 遍历元素
var mapHaiCoder sync.Map
mapHaiCoder.Store("Server", "Golang")
mapHaiCoder.Store("JavaScript", "Vue")
mapHaiCoder.Store("Db", "Redis")
mapHaiCoder.Range(walk)
}
程序运行后,控制台输出如下:
我们创建了一个 sync.Map,创建完之后,使用 Store 存储了三个元素,接着,我们使用 Range 遍历定义的 sync.Map。
遍历使用的函数,是我们自定义的 walk 函数,该返回接受两个 interface 类型的参数 ,返回一个 bool 类型的结果,返回 ture,表明元素遍历结束。
使用 sync.Map Range 遍历元素,返回 false,终止遍历
package main
import (
"fmt"
"sync"
)
func walk(key, value interface{}) bool {
fmt.Println("Key =", key, "Value =", value)
return false
}
func main() {
fmt.Println("嗨客网(www.haicoder.net)")
//使用 sync.Map Range 遍历元素,返回 false,终止遍历
var mapHaiCoder sync.Map
mapHaiCoder.Store("Server", "Golang")
mapHaiCoder.Store("JavaScript", "Vue")
mapHaiCoder.Store("Db", "Redis")
mapHaiCoder.Range(walk)
}
程序运行后,控制台输出如下:
我们在遍历使用的函数 walk 中,返回了 false,那么只会遍历一个元素,因为 false,表明我们需要终止遍历。
Go 语言中 sync.Map 的元素遍历,不可以使用 for 循环或者 for range 循环,而是使用 Range 配合一个回调函数进行遍历操作。Go 语言 sync.Map Range 语法:
func (m *Map) Range(f func(key, value interface{}) bool)