英文:
How use interface in function, where argument is another interface, that have same list of functions?
问题
我在函数参数中遇到了接口的问题。
package main
import (
"fmt"
)
type A interface {
New() A
B()
C()
}
type B interface {
New() B
B()
}
type AS struct{}
func (AS) New() A {
return AS{}
}
func (AS) B() {}
func (AS) C() {}
func Hello(b B) {
b.New()
}
func main() {
fmt.Println("Hello, playground")
as := AS{}
a := A(as)
Hello(a)
}
我遇到了以下错误:
tmp/sandbox293137995/main.go:35: cannot use a (type A) as type B in argument to Hello:
A does not implement B (wrong type for New method)
have New() A
want New() B
如果我想在函数Hello中使用接口A,我该如何重构这段代码呢?谢谢!
英文:
I have trouble with interfaces in function arguments.
package main
import (
"fmt"
)
type A interface {
New() A
B()
C()
}
type B interface {
New() B
B()
}
type AS struct {}
func (AS) New() A {
return AS{}
}
func (AS) B() {}
func (AS) C() {}
func Hello(b B) {
b.New()
}
func main() {
fmt.Println("Hello, playground")
as := AS{}
a := A(as)
Hello(a)
}
I've got this error:
tmp/sandbox293137995/main.go:35: cannot use a (type A) as type B in argument to Hello:
A does not implement B (wrong type for New method)
have New() A
want New() B
How can I refactor this code, if I want use interface A in function Hello?
Thanks!
答案1
得分: 2
如果你想要在任何接受接口B
的地方都能使用接口A
,那么A
必须实现B
中定义的所有方法。这包括New() B
和B()
。
实际上,你可以这样在A
中嵌入B
:
type A interface {
NewA() A
C()
B
}
你可以在这里找到一个可工作的示例。
请注意,在我的示例中,我仍然需要在AS
结构体中实现A
和B
的所有方法。
我还必须重命名这两个New()
函数。在Go语言中,即使两个函数的返回值不同,也不能在同一个包中有相同的函数名。
一般来说,在接口中不需要提供构造函数,因为可以在没有构造函数的情况下创建结构体。
英文:
If you wanted to able to use interface A
anywhere that interface B
is accepted, A
has to implement all the methods defined in B
. So that includes New() B
and B()
.
Essentially, you can embed B
in A
like this:
type A interface {
NewA() A
C()
B
}
You can find a working example here.
Notice that in my example, I still have to implement all the methods of both A
and B
in the AS
struct.
I also have to rename the 2 New()
functions. In Go, you can't have 2 functions in the same package with the same name, even though their return values are different.
In general, you don't need to provide constructors in interface, because structs can be created without them.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论