golang/go

Why seemingly equivalent types are said to be incompatible?

Closed this issue · 2 comments

I have this code:

type IA[T any] interface{ aaa(a IA[T]) }
type IB[T any] interface{ aaa(a IB[T]) }

func abc[T any](ia IA[T]) IB[T] {
	return ia
}

return ia is highlighted with the following error:

cannot use ia (variable of interface type IA[T]) as IB[T] value in return statement: IA[T] does not implement IB[T] (wrong type for method aaa)
		have aaa(IA[T])
		want aaa(IB[T])compiler[InvalidIfaceAssign](https://pkg.go.dev/golang.org/x/tools/internal/typesinternal#InvalidIfaceAssign)

However my understanding is that interfaces are compared structurally, and creating a named type for interface doesn't change anything, i.e. it doesn't matter. Why does the compiler report this error?

P.S. The following has no errors:

type IA[T any] interface{ aaa(a T) }
type IB[T any] interface{ aaa(a T) }

func abc[T any](ia IA[T]) IB[T] {
	return ia
}

Related Discussions

(Emoji vote if this was helpful or unhelpful; more detailed feedback welcome in this discussion.)

Unlike many projects, the Go project does not use GitHub Issues for general discussion or asking questions.

For questions please refer to https://github.com/golang/go/wiki/Questions