英文:
How to make a 2-level depth type definition in a struct?
问题
目前我有以下结构体的定义:
type WholeJson struct {
Features []Temp
}
type Temp struct {
Properties Human
}
type Human struct {
Name string
Age uint
}
当将一个JSON字符串解组成类型为WholeJson
的变量时,它可以正常工作。JSON字符串的结构如下:
{
"features":[
{
"properties": {
"name": "John Doe",
"age": 50
}
}
]
}
在Go Playground上的示例代码可以在这里找到:https://play.golang.org/p/3WTLxR0EZWP
但我不知道如何以更简单的方式编写它。显然,WholeJson
和Temp
两者都不是必需的,只要使用它们将要保存的信息即可。我之所以有Temp
,只是因为我不知道如何避免定义它(并且仍然使程序正常工作)。
假设WholeJson
的Features
属性将有一个指向某个interface{}
的数组,但我无法确定语法。我假设从解组数据的代码(来自playground示例)将保持不变。
我应该如何将这两个结构体"压缩"成一个结构体(我假设Human
结构体保持不变),并且最终仍然具有有用的数据,以便我可以通过features
键循环遍历所有数据?
英文:
Currently I have the following definition for my structs:
type WholeJson struct {
Features []Temp
}
type Temp struct {
Properties Human
}
type Human struct {
Name string
Age uint
}
Which is working when unmarshaling a JSON string into a variable of type WholeJson
, which would have the following structure:
{
"features":[
{
"properties": {
"name": "John Doe",
"age": 50
}
}
]
}
Go Playground sample here: https://play.golang.org/p/3WTLxR0EZWP
But I don't know how to write it in a simpler way. It is obvious that not both WholeJson
and Temp
are necessary as far as using the information they will hold. The only reason I have Temp
is because I simply don't know how to avoid defining it (and still have the program work).
Presumably the Features
property of WholeJson
would have an array to some interface{}
, but I can't nail the syntax. And I'm assuming the code for reading the unmarshalled data (from the playground sample) will stay the same.
How would I "squash" those those two structs into one (the Human
struct i'm assuming is okay if it stays on its own), and still have useful data in the end, where I could loop through the features
key to go through all the data?
答案1
得分: 3
在构建Go代码时,为层次结构的每个级别定义一个类型是可以的,并且是首选的。这些类型不需要被导出。
使用匿名类型来消除定义的类型:
var sourceData struct {
Features []struct {
Properties Human
}
}
var jsonString string = `{
"features":[
{
"properties": {
"name": "John Doe",
"age": 50
}
}
]
}`
json.Unmarshal([]byte(jsonString), &sourceData)
fmt.Println(sourceData.Features[0].Properties.Name)
英文:
It's OK to define a type for each level of the hierarchy and preferred when constructing values from Go code. The types do not need to be exported.
Use anonymous types to eliminate the defined types:
var sourceData struct {
Features []struct {
Properties Human
}
}
var jsonString string = `{
"features":[
{
"properties": {
"name": "John Doe",
"age": 50
}
}
]
}`
json.Unmarshal([]byte(jsonString), &sourceData)
fmt.Println(sourceData.Features[0].Properties.Name)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论