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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 adb连接不到手机是怎么回事?
  • ¥15 vs2022无法联网
  • ¥15 TCP的客户端和服务器的互联
  • ¥15 VB.NET操作免驱摄像头
  • ¥15 笔记本上移动热点开关状态查询
  • ¥85 类鸟群Boids——仿真鸟群避障的相关问题
  • ¥15 CFEDEM自带算例错误,如何解决?
  • ¥15 有没有会使用flac3d软件的家人
  • ¥20 360摄像头无法解绑使用,请教解绑当前账号绑定问题,
  • ¥15 docker实践项目