如何在切片内设置结构的字段?

I declared a type like this

type Klabel struct {
    values []float64
    label  string
}

Then, I created a slice of this type like this

kdata := []Klabel

How can I set the label variable or append a slice of floats to values?

I tried

kdata[0].label = "test"

and

kdata := make([]Klabel, 10)

kdata[0].label = "test"

and

kdata = append(kdata[0], kdata[0].label = "test")

Well, with no success...

So any help is appreciated! Thanks in advance!

You posted this:

kdata := make([]Klabel, 10)

kdata[0].label = "test"

And it works. When printing the kdata slice, output is (Go Playground):

[{[] test} {[] } {[] } {[] } {[] } {[] } {[] } {[] } {[] } {[] }]

The output shows kdata has 10 elements, and the first has the label value: "test".

To be more clear, print it with:

fmt.Printf("%+v", kdata)

Output:

[{values:[] label:test} {values:[] label:} {values:[] label:} {values:[] label:} {values:[] label:} {values:[] label:} {values:[] label:} {values:[] label:} {values:[] label:} {values:[] label:}]

Slices (unlike maps) are addressable. You can change the fields of the elements (that are structs) by simply indexing the slice and assigning new values to the fields.

For example:

kdata[0].label = "test"
kdata[0].values = []float64{1.1, 2.2}
kdata[0].values = append(kdata[0].values, 3.3)

fmt.Printf("%+v", kdata[0])

Output:

{values:[1.1 2.2 3.3] label:test}

If you want to append a slice of floats to the values field of an element:

vals := []float64{1.2, 2.3}

kdata[0].values = append(kdata[0].values, vals...) // Note the 3 dot ...

As an alternative to the other answer, you could also do this:

kdata := []Klabel{{label: "test"}}

(See on Go Playground)

But note that the slice length will be 1 rather than 10, so it's not exactly equivalent.