问题描述
我知道 Go 中有 struct,但就我所知,你必须定义 struct
I know there is struct in Go, but for all I know, you have to define struct
type Circle struct{
x,y,r float64
}
我想知道如何声明结构中不存在的新变量
I am wondering how you can declare a new variable that doesn't exist in the struct
circle := new(Circle)
circle.color = "black"
推荐答案
map[string]interface{}
map[string]interface{}
// Initial declaration
m := map[string]interface{}{
"key": "value",
}
// Dynamically add a sub-map
m["sub"] = map[string]interface{}{
"deepKey": "deepValue",
}
将 JSON 解组为地图如下所示:
Unmarshalling JSON into a map looks like:
var f interface{}
err := json.Unmarshal(b, &f)
f
f
f = map[string]interface{}{
"Name": "Wednesday",
"Age": 6,
"Parents": []interface{}{
"Gomez",
"Morticia",
},
}
你需要使用类型断言来访问它,否则 Go 不会知道它是一个地图:
You will need to use a type assertion to access it, otherwise Go won't know it's a map:
m := f.(map[string]interface{})
您还需要在从地图中拉出的每个项目上使用断言或类型开关.处理非结构化 JSON 很麻烦.
You will also need to use assertions or type switches on each item you pull out of the map. Dealing with unstructured JSON is a hassle.
更多信息:
这篇关于Golang动态创建结构体成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!