在 Golang 中封装 `sort` 接口

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


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))

    ...

}

有没有办法将 3 个方法定义(Len、Swap、 和Less)移动到Bar函数中,在 Go 中定义一个匿名方法?


// Something like this

func Bar() {

    ...

    Len := func (a byName)() int { return len(a) }

}

可以从这个包的外部访问在顶层定义的 3 个方法吗?我猜不是,因为类型byName是本地的。


沧海一幻觉
浏览 171回答 1
1回答

慕仙森

简单的回答,不,Go 中没有匿名方法之类的东西。由于匿名函数不能使用接收器声明,它们实际上不是方法,因此该byName类型不会实现所需的sort.Interface.
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go