【问题标题】:cannot use &ingredients (type *[]foo.bar) as type []*foo.bar in assignment不能在赋值中使用 &ingredients (type *[]foo.bar) 作为 type []*foo.bar
【发布时间】:2020-09-13 09:46:30
【问题描述】:

我使用 GoLang v1.5.1,我收到了这个奇怪的错误,或者我错过了一些东西。

在一个名为模型的包中,我定义了以下内容:

type SearchResultRow struct {
    ID          int               `json:"id"`
    Name        string            `json:"name"`
    Type        string            `json:"type"`
    Notes       *string           `json:"notes"`
    AddedBy     *string           `json:"added_by"`
    Source      *string           `json:"source"`
    Ratings     *int              `json:"ratings"`
    IVer        *int              `json:"i_ver"`
    Ingredients []*IngredientType `json:"ingredients"`
    Accessories []*AccessoryType  `json:"accessories"`
}

type AccessoryType struct {
    ID   int    `json:"id"`
    Name string `json:"name"`
    IVer *int   `json:"i_ver"`
}

type IngredientType struct {
    Name   string  `json:"name"`
    Flavor *string `json:"flavor"`
    ItID   *int    `json:"it_id"`
    IID    *int    `json:"i_id"`
    IVer   *int    `json:"i_ver"`
}

在我的主代码中

    var currentFinalRow model.SearchResultRow
    var ingredients []model.IngredientType
    ...
    err = json.Unmarshal(row.Ingredients, &ingredients)
    if err != nil {
        return nil, err
    }
    currentFinalRow.Ingredients = &ingredients

我得到了错误:cannot use &ingredients (type *[]model.IngredientType) as type []*model.IngredientType in assignment

我错过了什么吗?不是同一种吗?

【问题讨论】:

    标签: go variable-assignment


    【解决方案1】:

    一个是指向切片的指针,一个是指针切片。

    要解决问题,请将var ingredients []model.IngredientType 更改为var ingredients []*model.IngredientType,使其与结构字段的类型相匹配。然后将赋值改为currentFinalRow.Ingredients = ingredients,不带“address-of”运算符。

    一个(更短的)替代方案是 err = json.Unmarshal(row.Ingredients, &currentFinalRow.Ingredients),以便 json 解组直接在您的结构字段上工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-02
      • 2021-12-10
      • 1970-01-01
      • 1970-01-01
      • 2020-07-25
      • 2015-04-22
      • 2020-01-12
      • 1970-01-01
      相关资源
      最近更新 更多