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!
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.