go - 如何使用 Go 创建类似 Python 的字典?

标签 go

我正在尝试制作一个类似 Python 的字典。我试过:

var chunk = map[string]string{
    "code": "5000",
    "error": err,
}

var payload = map[string]string{
    "type": "response",
    "error": chunk,
}

我也试过

    var payload = map[string]string{
    "type": "response",
    "error": {
        "code": "5000",
        "error": err,
    },
}

最佳答案

Go 是一种静态类型语言。所以你不能创建动态 map 。您将 map 定义为 map[string]string,因此您的 map 键和值需要是字符串。

您可以使用 map[string]interface{} 来动态使用 map 。但无论何时使用该值,都需要将其转换为所需的类型。

举个例子

chunk := map[string]interface{}{
    "code": "5000",
    "error": err,
    "a": 5,
    "b": 7,
}

intvalue := chunk["a"].(int)

关于go - 如何使用 Go 创建类似 Python 的字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39071416/

相关文章:

forms - http.Request r.FormValue 什么都不返回/map[]

go - 无效的ClientTokenId : The security token included in the request is invalid

amazon-web-services - route53 列表托管区域输出抛出 "does not support indexing"错误

git - 如何在系统中没有安装git的情况下安装golang包?

ajax - 如何使用ajax从go api检索数据?

google-app-engine - 在 App Engine 中使用 rpc/jsonrpc

戈朗 : runtime error: invalid memory address or nil pointer dereference

lua - 如何: Communicate with a subprocess

unit-testing - 如何并行运行需要不同环境变量值的测试

go - 如何停止正在监听 RethinkDB 变更源的 goroutine?