I'm struggling to understand why the following code cannot be compiled:
package main
import "fmt"
type A interface {
Hello() B
}
type B interface {
World()
}
type AStruct struct{}
func (a AStruct) Hello() BStruct {
return BStruct{}
}
type BStruct struct{}
func (b BStruct) World() {}
func build(a A) {
fmt.Println("hello")
}
func main() {
a := AStruct{}
build(a)
}
The compilation error is:
cannot use a (variable of type AStruct) as A value in argument to build: AStruct does not implement A (wrong type for method Hello) have Hello() BStruct want Hello() B
If I change func (a AStruct) Hello() B, the error is gone. Shouldn't BStruct implement the B interface?
<< UPDATED CODE >>
How shall I modify the code if the interface definition and the methods are in different packages.
packX.go
package packX
import "fmt"
import "packY"
type A interface {
Hello() B
}
type B interface {
World()
}
func build(a A) {
fmt.Println("hello")
}
func read() {
a := packY.AStruct{}
build(a)
}
and the packY.go
package packY
type AStruct struct{}
func (a AStruct) Hello() BStruct {
return BStruct{}
}
type BStruct struct{}
func (b BStruct) World() {}
If I change func (a AStruct) Hello() BStruct to func (a AStruct) Hello() packX.B, then I have circular import.
Go type system uses strict function signature matching: if an interface method is declared to return
B, then a type method implementing that interface must returnB, and not a type that implementsB.