Equivalent Interfaces - why does this fail to compile?

170 views
Skip to first unread message

Amnon

unread,
May 24, 2021, 2:20:51 AM5/24/21
to golang-nuts
See https://play.golang.org/p/5x9JrD55WKc

The interfaces aer and ber look equivalent.
Both contain a function which returns nothing called m1
and a function which returns another an instance of the interface m2.

If we comment out m2, then the code will compile.
But otherwise we get an error:

./prog.go:14:5: cannot use a (type aer) as type ber in argument to bar: aer does not implement ber (wrong type for m2 method) have m2() aer want m2() ber

even though aer and ber should be equivalent!

package main

type aer interface {
m1()
m2() aer
}

type ber interface {
m1()
m2() ber
}

func Foo(a aer) {
bar(a)
}

func bar(b ber) {
}

func main() {
}

Axel Wagner

unread,
May 24, 2021, 3:54:15 AM5/24/21
to Amnon, golang-nuts
This is answered in the FAQ: https://golang.org/doc/faq#covariant_types

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/4112dd4a-f2b3-4469-806e-233f242f93f9n%40googlegroups.com.

Alexander Verbitsky

unread,
May 24, 2021, 12:08:07 PM5/24/21
to golang-nuts

Interfaces are not equal: "m2() aer" and "m2() ber" has different return type. Even compiler told you about it.

Amnon

unread,
May 24, 2021, 5:05:41 PM5/24/21
to golang-nuts
yes, but surely the return types are equivalent?

Axel Wagner

unread,
May 24, 2021, 5:40:51 PM5/24/21
to Amnon, golang-nuts
No, they are not. They are both defined types and as such, are not identical.

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
Reply all
Reply to author
Forward
0 new messages