如何漂亮地打印同步地图的内容



我想在 Go 中漂亮地打印同步映射的内容。 我有一个同步。地图data我想打印它的内容。

要查看特定键的值SiteData我可以运行以下代码。

var data sync.Map
siteData := map[string]string{"Name": "StackOverflow"}
data.Store("SiteData", siteData)
temp, _ := data.Load("SiteData") 
b, _ := json.MarshalIndent(temp, "", " ")
fmt.Println(string(b))

但我希望一次打印整个地图。这是因为data可以有很多键,我想一次打印它们。

运行以下代码不起作用并打印{}

var data sync.Map
siteData := map[string]string{"Name": "StackOverflow"}
data.Store("SiteData", siteData)
b, _ := json.MarshalIndent(data, "", " ")
fmt.Println(string(b))

sync.Map的字段(内部(不会导出,因此无法访问它们,更重要的是,如果不进行同步,则无法访问它们。因此,您不能只打印sync.Map的内容。

你可以做的是遍历你的sync.Map的所有条目,从中构建一个"普通"地图,并显示它。请注意,"普通"映射必须具有string密钥类型(encoding/json包不支持具有interface{}密钥类型的映射(。我们可以简单地使用interface{}将密钥转换为stringfmt.Sprint().要获取所有条目,您可以使用Map.Range().

例如:

var data sync.Map
data.Store("SiteData", map[string]string{
"Name": "StackOverflow",
"Url":  "https://so.com",
})
data.Store("Else", "something else")
m := map[string]interface{}{}
data.Range(func(key, value interface{}) bool {
m[fmt.Sprint(key)] = value
return true
})
b, err := json.MarshalIndent(m, "", " ")
if err != nil {
panic(err)
}
fmt.Println(string(b))

这将输出(在Go Playground上尝试(:

{
"Else": "something else",
"SiteData": {
"Name": "StackOverflow",
"Url": "https://so.com"
}
}

这是一个简单的 util 函数(您可以根据需要对其进行修改(:

// print map's key/value, with index (not stable),
func PrintSyncMap(m sync.Map) {
// print map,
fmt.Println("map content:")
i := 0
m.Range(func(key, value interface{}) bool {
fmt.Printf("t[%d] key: %v, value: %vn", i, key, value)
i++
return true
})
}

示例输出:

map content:
[0] key: Qian, value: class 2
[1] key: Zhao, value: class 1
[2] key: Li, value: class 4

技巧:

  • 指数不稳定。(又名。打印项目的顺序可能会在多个调用之间更改。

最新更新