将值分配给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.

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