我选择Golang并且在遍历链接列表时遇到了问题。我打算做的是访问链表的所有节点,并从每个节点调用一个接口方法。
我已经定义了一个界面
type Sortable interface {
CompareTo(t Sortable) int
}
我已经定义了节点类型和链接列表
type node struct {
pNext *node
value int
}
type LinkedList struct {
PHead, PNode *node
}
func (n node) CompreTo(t Sortable) int{
other := t.(node)
if n.value == other.value {
return 0
} else if n.value > other.value {
return 1
} else {
return -1
}
}
当我在遍历链表时进行比较时会出现问题: ......
PNode.CompareTo(PNode.pNext)
我得到: panic:接口转换:Sortable是* node,而不是node
猜测这是因为PNode和PNode.pNext是节点结构的指针,而不是节点对象?然后我应该如何投射指针以使其正确? 我曾经用C ++编写,所以也许我的策略在Golang世界出错了?
感谢任何建议!
答案 0 :(得分:1)
您必须将Sortable t
置为指针节点。
func (n node) CompreTo(t Sortable) int{
other := t.(*node)
if n.value == other.value {
return 0
} else if n.value > other.value {
return 1
} else {
return -1
}
}