douhunkuang8955 2019-03-10 20:15
浏览 23
已采纳

有没有更简单的方法来附加结构片段?

The following code works, but I want to find a simpler way to do it

package main

import "fmt"

type steps []struct {
    i int
    j int
}

func main() {
    steps := steps{}
    type step struct{ i, j int }
    steps = append(steps, step{1, 1}, step{1, 2})
    fmt.Println(steps)
}

Specifically, I don't want to define a new type just so I can append it to a slice. For example, I want to do it like this:

package main

import "fmt"

type steps []struct {
    i int
    j int
}

func main() {
    steps := steps{}
    steps = append(steps, {1, 1}, {1, 2}) // syntax error
    fmt.Println(steps)
}

But I'll get a "syntax error: unexpected {, expecting expression"

I don't understand why I can't do it this way, the data structure is correct.

  • 写回答

1条回答 默认 最新

  • douzhi3105 2019-03-10 20:30
    关注

    You created an anonymous struct in your slice, so you need to repeat the schema when adding elements:

    // works - but a bit tedious...
    steps = append(steps,
            struct {
                i int
                j int
            }{1, 1},
            struct {
                i int
                j int
            }{1, 2},
    )
    

    or define the sub-type:

    type step struct {
        i int
        j int
    }
    type steps []step
    
    steps = append(steps, step{3, 4}, step{5, 6})
    

    playground example

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 表达式必须是可修改的左值
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题