问题描述:
test.go:
package main
import "fmt"
import "sync"
var syncMapTest sync.Map
func getSyncMapLen(smap sync.Map) int {
count := 0
smap.Range(func(key, value interface{}) bool {
count++
return true
})
return count
}
func main() {
syncMapTest.Store(1, 2)
if getSyncMapLen(syncMapTest) != 0 {
fmt.Printf("len :%d \n", getSyncMapLen(syncMapTest))
} else {
fmt.Printf("len 0 \n")
}
}
:go vet 检查报错:
go vet test.go
#command-line-arguments
./test.go:7:25: getSyncMapLen passes lock by value: sync.Map contains sync.Mutex
./test.go:18:21: call of getSyncMapLen copies lock value: sync.Map contains sync.Mutex
./test.go:19:49: call of getSyncMapLen copies lock value: sync.Map contains sync.Mutex
原因分析:
go vet 工具会检测拥有 Lock 方法 (实际需要引用传递) 的 type 是否按值传递。如果是这种情况,则会发出警告。
解决方案:
把函数getSyncMapLen参数改成引用传递
test.go:
package main
import "fmt"
import "sync"
var syncMapTest sync.Map
func getSyncMapLen(smap *sync.Map) int {
count := 0
smap.Range(func(key, value interface{}) bool {
count++
return true
})
return count
}
func main() {
syncMapTest.Store(1, 2)
if getSyncMapLen(&syncMapTest) != 0 {
fmt.Printf("len :%d \n", getSyncMapLen(&syncMapTest))
} else {
fmt.Printf("len 0 \n")
}
}
参考:https://studygolang.com/articles/14479?fr=sidebar