-3

Situation

  • Bar has a method Get() with a signature *Foo
  • Foo implements 2 interfaces I_Venus1 and I_Mars1.
  • I_Venus2 has a method Get() with a signature I_Venus1
  • I_Mars2 has a method Get() with a signature I_Mars1.
type Foo struct {
}

type Bar struct {
}

func (*Bar) Get() *Foo {
    return nil
}

type I_Venus1 interface {
}

type I_Venus2 interface {
    Get() I_Venus1
}

type I_Mars1 interface {
}

type I_Mars2 interface {
    Get() I_Mars1
}

var _ I_Venus1 = &(Foo{}) // Foo meets I_Venus1 interface
var _ I_Mars1 = &(Foo{}) // Foo meets I_Mars1 interface

Problem

var _ I_Venus2 = &(Bar{}) // *Bar does not implement I_Venus2 (wrong type for method Get)
var _ I_Mars2 = &(Bar{})  // *Bar does not implement I_Mars2 (wrong type for method Get)

I do not understand what prevents the go compiler from deciding that Bar implements both I_Venus2 and I_Mars1 interfaces.

Note : this question is a variation on

Go Interface Method Returning Interface Doesn't Match Method Returning Concrete Type

4
  • Bar.Get() returns *Foo whereas I_Venus1.Get() returns I_Venus1 and I_Mars2.Get() returns I_Mars1. *FooI_Venus1I_Mars1 Commented Mar 2, 2024 at 10:18
  • @OluwafemiSule, I can see identifiers do not match. What I cannot understand is why, since the compiler decides that *Foo implements both interface, the compiler does not decide that Bar implements the interfaces with the method signature. It does not seem consistent to my eyes. Commented Mar 2, 2024 at 11:13
  • 2
    "I do not understand what prevents the go compiler from deciding that Bar implements both I_Venus2 and I_Mars1 interfaces." The language specification forbids the compiler to do so. Commented Mar 2, 2024 at 12:26
  • 3
    See also go.dev/doc/faq#covariant_types Commented Mar 2, 2024 at 12:52

1 Answer 1

-2

@peter has provided the good answer by pointing to go's FAQ.

Programmers who want covariant result types are often trying to express a type hierarchy through interfaces. In Go it's more natural to have a clean separation between interface and implementation.

Sign up to request clarification or add additional context in comments.

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.