一分耕耘,一分收获!既然都打开这篇《指向接口的指针INode*不同于接口》,就坚持看下去,学下去吧!本文主要会给大家讲到等等知识点,如果大家对本文有好的建议或者看到有不足之处,非常欢迎大家积极提出!在后续文章我会继续更新Golang相关的内容,希望对大家都有所帮助!
所以今天第一次尝试 go 并不断遇到与接口有关的错误,我想我没有正确理解它们。我尝试四处寻找答案,但我习惯的术语与其他语言有点不同,所以我无法将其拼凑在一起。作为实践,我决定实现一个非常简单的链表,但我收到的错误是:
调用 .setnext(node *inode) 时,type inode* 是指向接口的指针,而不是接口
这背后的原因是什么?我在界面中缺少哪些信息?
这是不完整的实现:
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
}解决方案
这是因为在 go 中,接口只是行为的规范。此行为可以使用指针接收器或值接收器来实现。接口并不关心最终使用哪一个,只要满足接口约定即可。
看这个例子: 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")
}
指向s类型和t类型的指针都实现了接口i,并且可以传递给任何需要i的func。接口并不关心它是否是指针。
您可以在这里阅读有关指针接收器的信息:https://tour.golang.org/methods/4
终于介绍完啦!小伙伴们,这篇关于《指向接口的指针INode*不同于接口》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!
本文内容来源于互联网,如有侵权请联系删除。
