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
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 自适应 LMS 算法实现 FIR 最佳维纳滤波器matlab方案
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥15 Python3.5 相关代码写作
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像