Implement Interface Method That Return Interface


(Jauhar Arifin) #1

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


(Norbert Melzer) #2

This should work (cant test):

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

(Jauhar Arifin) #3

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


(Norbert Melzer) #4

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