dongzhugao9929 2018-05-05 19:14 采纳率: 0%
浏览 56
已采纳

将值分配给struct golang中的struct时出错

I came across this situation where I was trying to assign values to a struct within a struct. There is no compiler error, but it does panic when you run it. Does Go have a different way to handle this data structure?

package main

import (
    "fmt"
)

type Label struct {
    ID     int
    Labels []struct {
        ID   int
        Name string
    }
}

func main() {
    l := Label{}
    l.ID = 100

    l.Labels[0].ID = 200
    l.Labels[0].Name = "me"

    fmt.Println(l.ID)
    fmt.Println(l.Labels[0].ID)
    fmt.Println(l.Labels[0].Name)
}

https://play.golang.org/p/IiuXpaDvF1W

Thanks in advance.

  • 写回答

1条回答 默认 最新

  • dongyi9023 2018-05-05 19:17
    关注

    The default value for a slice is nil so it has no elements, and you cannot assign to index 0 because it doesn't exist yet.

    You can use append to add a new element to that slice using:

    l.Labels = append(l.Labels, struct{
        ID   int
        Name string
    }{
        ID:   200,
        Name: "me",
    })
    

    https://play.golang.org/p/uAWdQdh0Ov7

    In addition, your use of an inline/anonymous struct here means you'll need to redeclare the type when you append. Consider adding another declared type:

    type SubLabel struct {
        ID   int
        Name string
    }
    
    type Label struct {
        ID     int
        Labels []SubLabel
    }
    
    // ...
    
    l.Labels = append(l.Labels, SubLabel{
        ID:   200,
        Name: "me",
    })
    

    https://play.golang.org/p/4idibGH6Wzd

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 能给我一些人生建议吗
  • ¥15 mac电脑,安装charles后无法正常抓包
  • ¥18 visio打开文件一直显示文件未找到
  • ¥15 请教一下,openwrt如何让同一usb储存设备拔插后设备符号不变?
  • ¥30 使用quartz框架进行分布式任务定时调度,启动了两个实例,但是只有一个实例参与调度,另外一个实例没有参与调度,不知道是为什么?请各位帮助看一下原因!!
  • ¥50 怎么获取Ace Editor中的python代码后怎么调用Skulpt执行代码
  • ¥30 fpga基于dds生成幅值相位频率和波形可调的容易信号发生器。
  • ¥15 R语言shiny包和ncdf4包报错
  • ¥15 origin绘制有显著差异的柱状图和聚类热图
  • ¥20 simulink实现滑模控制和pid控制对比,提现前者优势