duangua6912 2017-03-05 23:15
浏览 305
已采纳

自己类型的接口方法返回值

I am trying to make a method which will take structs of a certain type and do operations on them. However, I need to have a method one can call on an instance of the stuct, and it will return objects of that struct's type. I am getting a compile time error because the return type of the type which implements the interface isn't the same as the interface's method return type, but that's because the interface needs to return values of it's own type.

Interface declaration:

type GraphNode interface {
    Children() []GraphNode
    IsGoal() bool
    GetParent() GraphNode
    SetParent(GraphNode) GraphNode
    GetDepth() float64
    Key() interface{}
}

Type which implements that interface:

type Node struct {
    contents []int
    parent   *Node
    lock     *sync.Mutex
}

func (rootNode *Node) Children() []*Node {
...
}

Error Message:

.\astar_test.go:11: cannot use testNode (type *permutation.Node) as type GraphNode in argument to testGraph.GetGoal:
*permutation.Node does not implement GraphNode (wrong type for Children method)
have Children() []*permutation.Node
want Children() []GraphNode

Method to get parent:

func (node *Node) GetParent() *Node {
    return node.parent
}

The above method fails because it returns a pointer to a node, and the interface returns type GraphNode.

  • 写回答

1条回答 默认 最新

  • douningzhi1991 2017-03-06 01:21
    关注

    *Node doesn't implement the GraphNode interface because the return type of Children() isn't the same as that defined in the interface. Even if *Node implements GraphNode, you can't use []*Node where []GraphNode is expected. You need to declare Children() to return []GraphNode. The elements of a slice of type []GraphNode can be of type *Node.

    For GetParent(), just change it to this:

    func (node *Node) GetParent() GraphNode {
        return node.parent
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面