Suppose we have the following code
package main
type I1 interface {
Foo() string
}
type I2 interface {
Bar() I1
}
type S1 struct{}
func (s *S1) Foo() string {
return "foo"
}
type S2 struct{}
func (s *S2) Bar() *S1 {
return &S1{}
}
func main() {
x := &S2{}
var i I1 = x.Bar()
println(i.Foo())
var y I2
y = &S2{}
println(y.Bar().Foo())
}
Now, from my viewpoint S2
satisfies I2
, as the return of Bar()
satisfies I1
, as shown in the lines above, but the compiler disagrees with me:
# command-line-arguments
./main.go:28:4: cannot use S2 literal (type *S2) as type I2 in assignment:
*S2 does not implement I2 (wrong type for Bar method)
have Bar() *S1
want Bar() I1
Yes, I understand that they are different types† , but is that not sort of the point of an interface to accept any type that satisfies its requirements?
Can someone give more information as to what the technical reasons may be that the satisfaction of the interface is not taken into account at this stage?
The interface is not satisfied because the method signature does not match. The method signature specified in the interface is: Bar() I1 but the method signature provided is: Bar() *S1
you can still return a pointer to an S1 instance but you need the method signatures to match. Change the return type of the method to I1.