douzhang1955 2019-03-10 08:18
浏览 6
已采纳

将元帅提升为结构

I have two structs. One inherits from the other.

type Animal struct {
    Name string `json:"name"`
}

type Dog struct {
    Animal
    Color string `json:"color"`
}

When I go to Unmarshal to Dog by passing in:

{
  "name": "Loki",
  "color": "Brown"
}

I'm getting an *encoding/json.InvalidUnmarshalError. 2019/03/10 00:22:35 json: Unmarshal(nil *main.Dog)

Why is that?

Here's the unmarshal code:

func main() {
    var dog *Dog

    err := json.Unmarshal([]byte(`{
        "name": "Loki",
        "color": "Brown"
    }`), dog)

    if err != nil {
        log.Fatal(err)
    }
}
  • 写回答

2条回答 默认 最新

  • doukuangxun5382 2019-03-10 08:33
    关注

    That's because the variable dog is nil. Try to initialize it to point to an empty Dog. Or make it a Dog instead of a pointer to Dog and pass in the address to Unmarshal.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器