如何实现可以接受任何类型的链表,在golang上可以进行相等测试?

时间:2014-01-28 07:10:20

标签: interface go

我正在尝试在golang中实现链接列表。我希望链表能够存储可以执行相等测试的任何类型。

就像说,如果有,

type SimpleType struct {
    int
}
s := SimpleType{3}
m := SimpleType{4}

我希望能够做类似的事情,

if s == m {}if s < m以及其他相等测试。

我知道我可以使用接口完成此操作。比方说,我可以创建一个具有比较功能的接口,并使链接列表只接受具有接口类型的值。

但我想知道在Golang中是否有更好,更惯用的方法。

比如说,是否可以直接使用关系运算符<>==和co?

或者,如果那是不可能的,那么使用接口本身有更好的方法吗?

由于

1 个答案:

答案 0 :(得分:0)

我会说你应该将container/list与来自sort.Interface的想法结合起来。

基本上,在您的软件包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的实现,供你的algorythm使用 - 就像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用于按实现进行排序。

相关问题