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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?