封装Golang中的`sort`接口

huangapple go评论107阅读模式
英文:

Encapsulating `sort` Interface in Golang

问题

我正在尝试在Go语言中对一个结构体切片进行排序。我可以通过在包的顶层定义3个方法来实现sort.Interface接口:

  1. type byName []*Foo // 结构体Foo在另一个包中定义
  2. func (a byName) Len() int { return len(a) }
  3. func (a byName) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
  4. func (a byName) Less(i, j int) bool { return a[i].Name < a[j].Name }
  5. func Bar() {
  6. var foos []*Foo // 通过调用外部函数进行填充
  7. sort.Sort(byName(foos))
  8. ...
  9. }

有没有办法将这3个方法定义(LenSwapLess)移动到Bar函数中,在Go语言中定义一个匿名方法?

  1. // 类似这样
  2. func Bar() {
  3. ...
  4. Len := func(a byName) int { return len(a) }
  5. }

在这个包之外能否访问到在顶层定义的这3个方法?我猜测不能,因为类型byName是局部的。

英文:

I am trying to sort a slice of structs in Go. I can implement the sort.Interface by defining 3 methods at the top level of the package:

  1. type byName []*Foo // struct Foo is defined in another package
  2. func (a byName) Len() int { return len(a) }
  3. func (a byName) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
  4. func (a byName) Less(i, j int) bool { return a[i].Name &lt; a[j].Name }
  5. func Bar() {
  6. var foos []*Foo // Populated by a call to an outside function
  7. sort.Sort(byName(foos))
  8. ...
  9. }

Is there any way to move the 3 method definitions (Len, Swap, and Less) into the Bar function, defining an anonymous method in Go?

  1. // Something like this
  2. func Bar() {
  3. ...
  4. Len := func (a byName)() int { return len(a) }
  5. }

Can the 3 methods defined at the top level be accessed from outside of this package? I am guessing not, because the type byName is local.

答案1

得分: 2

简单回答,Go语言中没有匿名方法的概念。

由于无法使用接收器声明匿名函数,它们实际上不是方法,因此byName类型不会实现所需的sort.Interface接口。

英文:

Simple answer, no, there are no such things as anonymous methods in Go.

As anonymous functions cannot be declared using a receiver, they are effectively not methods, therefore the byName type would not implement the required sort.Interface.

huangapple
  • 本文由 发表于 2016年4月14日 04:07:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/36608557.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定