我会说你应该想法从sort.Interface
结合container/list
。
基本上,你的包mylist
您可以定义是这样的:
type ListItem struct {
...
}
type Interface interface {
func Less(a, b *ListItem) bool
func Equal(a, b *ListItem) bool
}
(func Greater(a, b *ListItem) bool
没有必要的,因为它只是!Less(a, b)
;同样适用于NotEqual()
) …然后实现你的名单上排序功能这将需要调用者提供Interface
的实施以供您的过期—使用,就像sort.Sort()
一样。
要实现的是你定义
func Sort(head *ListElement, comp Interface) *ListElement
它会使用列表的头,排序使用提供的比较,并返回排序列表的头部。 客户端将被要求提供一个比较,就像
import "github.com/Jay/mylist"
...
type Foo struct {
...
Id int // used for comparisons
...
}
type FooComp struct{}
func (FooComp) Less(a, b *mylist.ListItem) bool {
fa, fb := a.Value().(Foo), b.Value().(Foo)
return fa.Id < fb.Id
}
func (FooComp) Equal(a, b *mylist.ListItem) bool {
fa, fb := a.Value().(Foo), b.Value().(Foo)
return fa.Id == fb.Id
}
data := mylist.New()
head := mylist.PushBack(Foo{...})
// ... add more elements here
// Now sort the list using the comparator
head := mylist.Sort(head, FooComp{})
这里,客户端代码定义用于它自己的类型,Foo
,存储在您的列表,它比较,FooComp
按您的实施进行排序。