【问题标题】:How to append data to a Slice that is formatted by a Nested Struct如何将数据附加到由嵌套结构格式化的切片
【发布时间】:2020-03-06 14:35:47
【问题描述】:

我正在尝试将一些数据附加到基于我的结构的切片中。

在尝试这样做时,我尝试将我的结构拆分为两个独立的结构。这是不成功的。每次我尝试附加切片时,都会收到错误消息:missing type in composite literal。我试着用谷歌搜索,但我似乎无法弄清楚。


// Separate File in types folder
type Item struct {
    ID                 string `json:"id"`
    Item               string `json:"item"`
    ProductDescription []ProductDescription
}

// Separate File in types folder
type ProductDescription struct {
    ShortDescription    string `json:"short_description"`
}


//Items Slice holds ItemsDB
var Items []types.Item

func ItemsDB() {
    Items = append(Items,
        types.Item{
            ID:                 "1",
            Item:               "fruit",
            ProductDescription: {
                ShortDescription: "banana",
            },
        },
        types.CoreItem{
            ID:                 "1",
            Item:               "dairy",
            ProductDescription: {
                ShortDescription, "milk",
            },
        },
    )
}

预期的结果是:

{

{"id": "1", "item": "fruit", "product_descriptions": {"short_description": "banana"},

{"id": "1", "item": "fruit", "product_descriptions": {"short_description": "banana"}

}

【问题讨论】:

    标签: go struct append slice


    【解决方案1】:

    ProductDescription 是一个数组,你的语法是初始化一个结构。试试这个:

    ProductDescription: []types.ProductDescription{
       {  ShortDescription: "banana"}
     }
    

    【讨论】:

    • — 我尝试像下面这样执行上述操作,但不断收到 undefined: ProductDescription func ItemsDB() { Items = append(Items, types.Item{ ID: "1", Item: "fruit", ProductDescription: []ProductDescription{ {ShortDescription: "banana"}, }, } }
    • 你需要用包名来限定它,就像你用Item做的那样。
    • 看起来 ProductDescription 在 types 包中。我修复了答案以包含它。
    猜你喜欢
    • 1970-01-01
    • 2019-01-02
    • 2019-04-12
    • 1970-01-01
    • 1970-01-01
    • 2021-05-26
    • 2016-12-24
    • 2014-03-25
    • 2018-12-05
    相关资源
    最近更新 更多