封装Golang中的`sort`接口

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

Encapsulating `sort` Interface in Golang

问题

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

type byName []*Foo // 结构体Foo在另一个包中定义

func (a byName) Len() int           { return len(a) }
func (a byName) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a byName) Less(i, j int) bool { return a[i].Name < a[j].Name }

func Bar() {
    var foos []*Foo // 通过调用外部函数进行填充

    sort.Sort(byName(foos))
    ...
}

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

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

在这个包之外能否访问到在顶层定义的这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:

type byName []*Foo // struct Foo is defined in another package

func (a byName) Len() int           { return len(a) }
func (a byName) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a byName) Less(i, j int) bool { return a[i].Name &lt; a[j].Name }

func Bar() {
    var foos []*Foo // Populated by a call to an outside function

    sort.Sort(byName(foos))
    ...
}

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

// Something like this
func Bar() {
    ...
    Len := func (a byName)() int { return len(a) }
}

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:

确定