douzhongpi9734 2013-10-12 05:52
浏览 27
已采纳

Golang,Go:具有返回接口的映射?

http://golang.org/pkg/sort/

This is from Go example.

 // OrderedBy returns a Sorter that sorts using the less functions, in order.
// Call its Sort method to sort the data.
func OrderedBy(less ...lessFunc) *multiSorter {
    return &multiSorter{
        changes: changes,
        less:    less,
    }
}

What does this do by colon? Is it mapping? Is it closure? Too much new syntax here. What should I read to understand this syntax in Go?

  • 写回答

2条回答 默认 最新

  • duancoubeng5909 2013-10-12 06:08
    关注

    It's a factory function, creating and initialising a struct of type multisorter:

    https://sites.google.com/site/gopatterns/object-oriented/constructors

    Additionally, Go "constructors" can be written succinctly using initializers within a factory function:

    function NewMatrix(rows, cols, int) *matrix {
        return &matrix{rows, cols, make([]float, rows*cols)}
    }
    

    Also, it is using named parameters when initialising:

    http://www.golang-book.com/9

    This allocates memory for all the fields, sets each of them to their zero value and returns a pointer. (Circle) More often we want to give each of the fields a value. We can do this in two ways. Like this:

    c := Circle{x: 0, y: 0, r: 5}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
  • dongyanfeng0546 2013-10-15 05:43
    关注

    The `less ...lessFunc` in the func declaration means:

    any number of parameters, each of type `lessFunc` can be passed here, and will be stored in the slice `less`
    

    So it creates a `multiSorter` struct, which supports the sort interface, and calling the sort method from that interface (and implemented by multiSorter) will cause the object to use each lessFunc in turn while sorting

    Does this make sense? I can expand more if needed...

    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 有偿求做台风过境全过程模拟仿真
  • ¥50 求!AutomationDesk 如何自动导入Variant数据
  • ¥20 Next.JS 静态导出路由
  • ¥15 我做一个对中文文本情感分析的项目 我用了CNN,和keras框架 报的错误我一直处理不好
  • ¥15 unity使用bakery打光烘焙所遇到的问题。
  • ¥99 二维有限元方法求解,泊松方程
  • ¥15 我需要在PC端 开两个抖店工作台客户端.(语言-java)
  • ¥15 有没有哪位厉害的人可以用C#可视化呀
  • ¥15 可以帮我看看代码哪里错了吗
  • ¥15 设计一个成绩管理系统