可以通过调用sync.Map的Range方法来遍历所有元素,并通过计数器统计元素个数。示例如下:

package main

import (
	"fmt"
	"sync"
)

func main() {
	var m sync.Map
	m.Store("key1", "value1")
	m.Store("key2", "value2")
	m.Store("key3", "value3")

	count := 0
	m.Range(func(key, value interface{}) bool {
		count++
		return true
	})

	fmt.Println(count) // 输出:3
}

另外,也可以使用sync.Map的Load方法来获取某一个元素,但无法获取整个map的元素个数。

go 获取syncMap元素个数