Golang:地图界面,如何打印键和值

时间:2020-05-28 02:29:14

标签: go interface

我得到一个地图界面,例如:

getUsersAppInfo := usersAppInfo.GetUsersAppInfo(getUserId)

然后我打印:

fmt.Println(getUsersAppInfo)

获取此内容,例如:

[map[appId:2 fcmServerKey:keyTestTest name:com.app]]

询问:如何仅打印值,例如

appId value is 2 
name value is com.app 
fcmServerKey:keyTestTest value is keyTestTest 

3 个答案:

答案 0 :(得分:6)

OP对问题的评论指出getUsersAppInfo的类型为[]map[string]interface{}

在地图切片上环行。对于每张地图,请遍历键和值并进行打印。

// loop over elements of slice
for _, m := range getUsersAppInfo {

    // m is a map[string]interface.
    // loop over keys and values in the map.
    for k, v := range m {
        fmt.Println(k, "value is", v)
    }
}

Run this on the GoLang PlayGround

答案 1 :(得分:0)

恐怕唯一的选择是遍历地图:

getUsersAppInfo := map[string]interface{}{"foo": 3, "bar": "baz"}
for key, value := range getUsersAppInfo {
    fmt.Printf("%s value is %v\n", key, value)
}

答案 2 :(得分:0)

我不建议在生产设置中执行此操作。但是当我想在我的开发箱上打印出没有太多代码的地图时,我会打印JSON序列化版本。生产中将构成犯罪。

package main

import (
    "encoding/json"
    "fmt"
)

func main() {
    a := map[string]interface{}{"appId": 2, "fcmServerKey": "keyTestTest", "name": "com.app", "version": []int{1, 2, 3}, "xyz": 3}
    bs, _ := json.Marshal(a)
    fmt.Println(string(bs))
}

输出:

{"appId":2,"fcmServerKey":"keyTestTest","name":"com.app","version":[1,2,3],"xyz":3}