Implement Interface Method That Return Interface

https://play.golang.org/p/BCfG7-6IctI

package main

import "fmt"

type Barer interface {
	Bar() string
}

type Fooer interface {
	Foo() Barer
}

type bar struct {
}

func (bar) Bar() string {
	return "bar"
}

type foo struct {
}

func (foo) Foo() bar {
	return bar{}
}

func print(foo Fooer) {
	fmt.Println(foo.Foo().Bar())
}

func main() {
	x := foo{}
	print(x)
}

Why is this code failed to compile

./prog.go:33:7: cannot use x (type foo) as type Fooer in argument to print:
	foo does not implement Fooer (wrong type for Foo method)
		have Foo() bar
		want Foo() Barer

The func (foo) Foo() bar indeed return Barer, but bar is not detected as Barer

3 Likes

This should work (cant test):

func (foo) Foo() Barer {
	return bar{}
}
1 Like

Ya, I understand that it works. But I just want to know, why can’t we return the concrete struct instead of the interface.

1 Like

Because in the interface definition you say, that you want a method that returns a Barer, not a bar. Signatures need to match exactly.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.