如何在golang中初始化嵌套结构?

时间:2017-07-28 02:12:54

标签: go struct

type important struct {
client     string                 `json:"client"`
Response   Summary        `json:"response"`

}

type Summary struct {
Name     string           `json:"name"`
Metadata Clientdata      `json:"metadata"`
}

type Clientdata struct {
Income string           `json:"income"` 
}


v := &important{ client: "xyz", Response:  Summary[{
            Name: "test",
            Metadata: Clientdata { "404040"},
        }
    }]

//错误:无法使用摘要{名称:“测试”,元数据:Clientdata {“404040”},}(类型摘要)作为类型[]摘要更多...

我在这里做错了什么?

2 个答案:

答案 0 :(得分:1)

简单地说,你略微改变了切片文字的语法。你的错误是合乎逻辑的,但遗憾的是它不起作用。

以下是固定版本:

v := &important{ client: "xyz", Response: []Summary{
        {
            Name: "test",
            Metadata: Clientdata { "404040"},
        },
    },
}

切片文字的定义如下:

[]type{ items... }

答案 1 :(得分:0)

目前还不清楚你想要如何处理它,因为你的Response结构暗示了[] VmSummary信息,但你正在提供它[]摘要。

另外,检查数组初始化时的https://blog.golang.org/go-slices-usage-and-internals

那样的东西?

type important struct {
    client   string    `json:"client"`
    Response []Summary `json:"response"`
}

type Summary struct {
    Name     string     `json:"name"`
    Metadata Clientdata `json:"metadata"`
}

type Clientdata struct {
    Income string `json:"income"`
}

func main() {
    v := &important{
        client: "xyz",
        Response: []Summary{
            {
                Name:     "test",
                Metadata: Clientdata{"404040"},
            },
        },
    }
}
相关问题