【发布时间】:2019-05-19 15:46:33
【问题描述】:
我是 Golang 的新手。
我将创建一个可调整大小的字典列表(这不是静态的),并将一些dict 附加到list。然后我想把它写在一个文件上,但是我很困惑。
我想要这样的东西:
[
{"port": 161, "timeout": 1, "sleep_time": 5, "metrics": [
{"tag_name": "output_current", "id": 3},
{"tag_name": "input_voltage", "id": 2}
]},
{"port": 161, "timeout": 1, "sleep_time": 4, "metrics": [
{"tag_name": "destructor", "id": 10}
]}
]
[更新]:
Go 语言中的.append() Python 等价物是什么,比如下面的代码 sn-p?
list_ = []
dict_ = {"key": val}
list_.append(dict_)
我通过借用 this answer 找到了本节的答案([更新]):
type Dictionary map[string]interface{}
data := []Dictionary{}
dict1 := Dictionary{"key": 1}
dict2 := Dictionary{"key": 2}
data = append(data, dict1, dict2)
【问题讨论】:
-
你看过切片和地图吗?
-
是的,我做到了。那么 Golang 中不存在 list 和 dict 吗? Go 中的等价物是什么?
-
这是我的切片,这是我的地图。这是给列表的,这是给字典的。(抱歉没办法)。无论如何,“字典列表”在 Go 中转换为“地图切片”(我也会考虑结构)。
-
请浏览tour of Go covers
append部分。
标签: json list dictionary go