duanjia7607 2018-07-26 03:09
浏览 70

INode *类型是指向接口而不是接口的指针

So trying out go for the first time today and keep running into an error to do with interfaces, I guess I don't understand them correctly. Ive tried looking around for an answer but the terminology that I'm used to is a little different from other languages so I can't piece it together. As practice I decided to implement a very simple linked list but the error I recieve is:

type INode* is pointer to interface, not interface when calling .setNext(node *Inode)

What is the reason behind this? what piece of information am I missing with interfaces?

Heres the incomplete implementation:

package main

type object interface{}

type INode interface {
    GetData() object
    GetNext() *INode
    setNext(node *INode)
}

type ILinkedList interface {
    Link(node *INode)
    Unlink(node *INode)
    CurrentLength() int
    RemoveAt(idx int)
}

type Node struct {
    data object
    next *INode
}

func (n *Node) GetData() object {
    return n.data
}

func (n *Node) GetNext() *INode {
    return n.next
}

func (n *Node) setNext(node *INode) {
    n.next = node
}

type LinkedList struct {
    cur    *INode
    last   *INode
    length int
}

func (l *LinkedList) Link(node *INode) {
    if l == nil {
        return
    }
    if l.cur == nil {
        l.cur = node
        l.last = node
    } else {
        l.last.setNext(node)
        l.last = node
    }
    l.length = l.length + 1
}
  • 写回答

2条回答 默认 最新

  • doupapin172773 2018-07-26 03:57
    关注

    This is because in Go, an interface is just a specification of behavior. This behavior can be implemented with either a pointer receiver or a value receiver. The interface doesn't care which one is ultimately used, just as long as it fulfills the interface contract.

    See this example: https://play.golang.org/p/0AaBhB1MHBc

    type I interface {
        M()
    }
    
    type T struct {
        S string
    }
    func (t T) M(){
        fmt.Println("T.M fired");
    }
    
    type S struct {
        S string
    }
    func (s *S) M(){
        fmt.Println("*S.M fired");
    }
    
    func RunM(i I){
        i.M()
    }
    func main() {
        test1 := T{}
        test2 := &S{}
        RunM(test1)
        RunM(test2)
        fmt.Println("Hello, playground")
    }
    

    Both pointers to the S type and T types implement the interface I, and can be passed in to any func requiring an I. The interface doesn't care if it's a pointer or not.

    You can read up about pointer receivers here: https://tour.golang.org/methods/4

    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?