英文:
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个方法定义(Len
、Swap
和Less
)移动到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 < 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
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论