我知道围棋里有struct,但据我所知,你必须定义struct
type Circle struct{
x,y,r float64
}
我想知道如何声明 struct 中不存在的新变量
circle := new(Circle)
circle.color = "black"
我知道围棋里有struct,但据我所知,你必须定义struct
type Circle struct{
x,y,r float64
}
我想知道如何声明 struct 中不存在的新变量
circle := new(Circle)
circle.color = "black"
您需要使用映射(类型为map[string]interface{}
)来处理动态JSON.以下是创建新 map 的示例:
// Initial declaration
m := map[string]interface{}{
"key": "value",
}
// Dynamically add a sub-map
m["sub"] = map[string]interface{}{
"deepKey": "deepValue",
}
将JSON解组到映射中如下所示:
var f interface{}
err := json.Unmarshal(b, &f)
上面的代码将为您留下一个f
中的 map ,其 struct 类似于:
f = map[string]interface{}{
"Name": "Wednesday",
"Age": 6,
"Parents": []interface{}{
"Gomez",
"Morticia",
},
}
您需要使用类型断言来访问它,否则Go不会知道它是一个映射:
m := f.(map[string]interface{})
您还需要在从映射中拉出的每个项目上使用断言或类型switch .处理非 struct 化JSON是一件麻烦事.
更多信息: