dpjpo746884 2015-08-27 13:08
浏览 8
已采纳

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

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!

  • 写回答

2条回答 默认 最新

  • doushouj966020 2015-08-27 13:14
    关注

    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 ...
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥50 我撰写的python爬虫爬不了 要爬的网址有反爬机制
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等