【发布时间】:2016-11-02 12:54:55
【问题描述】:
出于学习目的,我正在使用 Go 开发一个简单的链表实现。元素的定义如下:
type Element struct {
next, prev *Element
Value interface{}
}
如您所见,Value 可以是任何满足空接口的东西。现在,作为一项新功能,我想这样做,以便当您将新元素插入列表时,它会以排序方式插入 - 每个元素都将是
为了做到这一点,我写了以下方法:
func (l *LinkedList) Add(val interface{}) *Element {
this := &l.Root
e := Element{Value: val}
for {
if this.next.Value != nil && this.next.Value < val { // <-comparison here
this = this.next
} else {
return l.insert(&e, this)
}
}
}
编译器抱怨operator < not defined on interface 这是公平的。所以我知道在我的 Element typedef 中,我应该将 Value 限制为可以使用 < 运算符进行比较的类型。我在研究 Go 不支持运算符重载的问题时了解到这一点——我不想这样做。相反,我只是想确保 Element.Value 是一种可以使用 < 运算符进行比较的类型。我该怎么做?
更新:
在我看来,简单地定义一个基于内置的新类型可能并不难,可以通过一些函数进行比较。所以我写了这个烂摊子(以及许多其他尝试做同样事情的方法):
type Comparable interface {
LessThan(j interface{}) bool // tried (j Comparable), (j MyInt), etc
EqualTo(j interface{}) bool // tried (j Comparable), (j MyInt), etc
}
type MyInt int
func (i MyInt) LessThan(j MyInt) bool {
return i < j
}
func (i MyInt) EqualTo(j MyInt) bool {
return i == j
}
type Element struct {
next, prev *Element
Value Comparable
}
我真正想要的是定义一个接口,如果为一个类型实现它,它提供函数LessThan 和EqualTo 操作该类型的两个实例并提供一个布尔值 - 类似于LessThan(i, j WhatEvers) bool可以用来代替<。我在下面意识到它是作为实例方法实现的 - 我尝试了两种方法但没有成功。有了上面的内容,我会在 Add 函数中使用类似:this.next.Value.LessThan(val)。我得到:
linkedlist.MyInt does not implement linkedlist.Comparable (wrong type for EqualTo method)
have EqualTo(linkedlist.MyInt) bool
want EqualTo(interface {}) bool
或
linkedlist.MyInt does not implement linkedlist.Comparable (wrong type for EqualTo method)
have EqualTo(linkedlist.MyInt) bool
want EqualTo(linkedlist.Comparable) bool
这是否可以使用接口来要求必须存在对自定义类型的两个实例进行操作的某个函数,还是仅用于方法?
【问题讨论】:
-
您是否看过标准的linked list 和sort 实现如何处理这个问题?
-
你不能。没有像“所有允许通过
标签: go interface linked-list comparison-operators