dtx9931 2017-04-07 09:43
浏览 211

为什么在Golang结构创建中出现逗号?

I have a struct:

type nameSorter struct {
    names []Name
    by    func(s1, s2 *Name) bool

Which is used in this method. What is going on with that comma? If I remove it there is a syntax error.

func (by By) Sort(names []Name) {
        sorter := &nameSorter{
            names: names,
            by:    by, //why does there have to be a comma here?
        }
        sort.Sort(sorter)

Also, the code below works perfectly fine and seems to be more clear.

func (by By) Sort(names []Name) {
    sorter := &nameSorter{names, by}
    sort.Sort(sorter)

For more context this code is part of a series of declarations for sorting of a custom type that looks like this:

By(lastNameSort).Sort(Names)
  • 写回答

1条回答 默认 最新

  • dop20345 2017-04-07 10:06
    关注

    This is how go works, and go is strict with things like comma and parentheses.

    The good thing about this notion is that when adding or deleting a line, it does not affect other line. Suppose the last comma can be omitted, if you want to add a field after it, you have to add the comma back.

    See this post: https://dave.cheney.net/2014/10/04/that-trailing-comma.

    评论

报告相同问题?

悬赏问题

  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在