dt3999 2019-06-27 11:26
浏览 255
已采纳

在Golang中将值追加到struct的struct会返回无效的内存地址

I have a meal struct that "appends" another struct, except I want to add another struct "mealComponents".

type mealMain struct {
    *model.Meal
    Components []mealComponent `json:"components"`
}

type mealComponent struct {
    *model.MealComponent
}

Where *model.Meal is as follows

type Meal struct {
    ID               int64     `json:"id"`
}

What I want is basically for "mealMain" struct to act like "Meal" struct, so that I can assign values and somehow append mealComponent as child (or maybe this is not a good idea? I'm open to suggestions)

However when I do something like this

var meal mealMain
meal.ID = 1

It throws runtime error: invalid memory address or nil pointer dereference at meal.ID assignment.

But if I do it like this:

type mealMain struct {
    MealMain *model.Meal `json:"meal_main"`
    Components []mealComponent `json:"components"`
}

Then assign it this way:

var meal mealMain
meal.mealMain.ID = 1

It works properly, but I have the return json even deeper like this:

{
    "MealModel": {
        "id": 1
    }
}

What I want is this:

{
    "id": 1
}

Note: I want to avoid changing the model.

  • 写回答

1条回答 默认 最新

  • doupin2013 2019-06-27 12:26
    关注

    If you don't want to change the model:

        var meal = mealMain{
            Meal: &Meal{},
        }
        meal.ID = 1
    

    The point is that in the following struct *Meal is set to nil if you don't initialize it.

    type mealMain struct {
        *Meal
        Components []mealComponent `json:"components"`
    }
    

    I'd probably create a function to never have to worry about the correct initialization ever again:

    func newMealMain() mealMain {
        return mealMain{
            Meal: &Meal{},
        }
    }
    

    Then your code would be:

        var meal = newMealMain()
        meal.ID = 1
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 逻辑谓词和消解原理的运用
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?