无法为放置在同一包中的多个结构实现接口方法。

huangapple go评论70阅读模式
英文:

Cannot implement interface methods for multiple structs placed in the same package

问题

我有三个文件:

node.go:

type Node interface {
	AMethod(arg ArgType) bool
	BMethod() bool
}

anode.go:

type aNode struct {}
    
func AMethod(aNode ANode, arg ArgType) bool {
	return true
}

func BMethod(aNode ANode) bool {
	return true
}

bnode.go:

type bNode struct {}
    
func AMethod(bNode BNode, arg ArgType) bool {
	return true
}

func BMethod(bNode BNode) bool {
	return true
}

但是我得到了错误:

Nodes/bnode.go:16:58: AMethod在此块中重新声明
	先前的声明在Nodes/anode.go:15:58
Nodes/bnode.go:20:60: BMethod在此块中重新声明
	先前的声明在Nodes/anode.go:19:60

在这里如何有效地实现一个接口?

英文:

I have three files:

node.go:

type Node interface {
	AMethod(arg ArgType) bool
	BMethod() bool
}

anode.go:

type aNode struct {}
    
func AMethod(aNode ANode, arg ArgType) bool {
	return true
}

func BMethod(aNode ANode) bool {
	return true
}

bnode.go:

type bNode struct {}
    
func AMethod(bNode BNode, arg ArgType) bool {
	return true
}

func BMethod(bNode BNode) bool {
	return true
}

But I'm getting the error:

Nodes/bnode.go:16:58: AMethod redeclared in this block
	previous declaration at Nodes/anode.go:15:58
Nodes/bnode.go:20:60: BMethod redeclared in this block
	previous declaration at Nodes/anode.go:19:60

How do I validly implement an interface here?

答案1

得分: 3

声明一个接受特定类型的函数并不会使该函数成为类型的方法集的一部分(也就是说,它不能帮助该类型满足特定的接口)。

相反,你需要使用正确的语法来声明一个函数作为方法,像这样:

type BNode struct {}

func (ANode) AMethod(arg ArgType) bool {
    return true
}

func (ANode) BMethod() bool {
    return true
}

type BNode struct {}

func (BNode) AMethod(arg ArgType) bool {
    return true
}

func (BNode) BMethod() bool {
    return true
}
英文:

Declaring a function that accepts a certain type does not make that function part of the type's method set (meaning it does not help the type satisfy a particular interface).

Instead, you need to use the proper syntax to declare a function as a method, like so:

type BNode struct {}

func (ANode) AMethod(arg ArgType) bool {
    return true
}

func (ANode) BMethod() bool {
    return true
}

type BNode struct {}

func (BNode) AMethod(arg ArgType) bool {
    return true
}

func (BNode) BMethod() bool {
    return true
}

huangapple
  • 本文由 发表于 2017年9月1日 21:46:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/46001611.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定