douzhoubing2805 2018-08-12 12:14
浏览 54
已采纳

向切片添加匿名struct元素

let's say I have a slice of anonymous structs

data := []struct{a string, b string}{}

Now, I would like to append a new item to this slice.

data = append(data, ???)

How do I do that? Any ideas?

  • 写回答

1条回答 默认 最新

  • dourao3960 2018-08-12 12:17
    关注

    Since you're using an anonymous struct, you have to again use an anonymous struct, with identical declaration, in the append statement:

    data = append(data, struct{a string, b string}{a: "foo", b: "bar"})
    

    Much easier would be to use a named type:

    type myStruct struct {
        a string
        b string
    }
    
    data := []myStruct{}
    
    data = append(data, myStruct{a: "foo", b: "bar"})
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥30 自适应 LMS 算法实现 FIR 最佳维纳滤波器matlab方案
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥15 Python3.5 相关代码写作
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动