【问题标题】:Golang struct pointer invokes interface methodGolang结构指针调用接口方法
【发布时间】:2018-02-09 05:33:26
【问题描述】:

我正在使用 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)

我得到: 恐慌:接口转换:可排序的是*节点,而不是节点

猜这是因为 PNode 和 PNode.pNext 是指向节点结构的指针,而不是节点对象?那么我应该如何投射指针以使其正确? 我以前用 C++ 编写,所以也许我的策略在 Golang 世界中出错了?

感谢任何建议!

【问题讨论】:

    标签: go struct go-interface


    【解决方案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
        }
    }
    

    【讨论】:

    • 虽然CompareTo 被声明在node 上,但这确实使Sortable 成为指向node 的指针,而不是node。语言规范的哪一部分谈到了这一点?
    猜你喜欢
    • 1970-01-01
    • 2015-01-26
    • 1970-01-01
    • 2019-06-26
    • 2016-10-15
    • 1970-01-01
    • 1970-01-01
    • 2014-07-30
    • 1970-01-01
    相关资源
    最近更新 更多