Is it necessary to import interface definition package?

I’m learning Golang, the design is pretty.
But while I try separating interface definition and implementation, I meet compile error:

.\main.go:16: cannot use new(dog.Dog) (type *dog.Dog) as type animal.Animal in assignment:
*dog.Dog does not implement animal.Animal (wrong type for Born method)
have Born() *dog.Dog
want Born() animal.Runner

While, if the “iface/animal” is imported in dog.go, and the Run function return type is animal.Runner, everything is fine, but it’s ugly.

Is it necessary to import interface definition package?

Source code:

// animal.go
package animal

type Animal interface {
Born() Runner
}

type Runner interface {
Run()
}

// dog.go
package dog

type Dog struct {
}

func (d *Dog) Born() *Dog {
dd := new(Dog)
return dd
}

func (d *Dog) Run() {
}

// iface project main.go
package main

import (
“fmt”

"iface/animal"
"iface/dog"

)

var (
dd animal.Animal
)

func main() {
dd = new(dog.Dog)

fmt.Printf("%t %v\n", dd, dd)

}

*dog.Dog does not implement animal.Animal (wrong type for Born method)
		have Born() *dog.Dog
		want Born() animal.Runner

In Go, method signatures must match precisely for an interface to be satisfied. That means that even though a type *dog.Dog may implement the animal.Runner interface on it’s own, a method func Born() *dog.Dog does not implement an interface expecting a func Born() animal.Runner.

Thanks Jakob.

It’s understandable that current method signature checking is not recursively.

I mean it still looks ugly, and violate the base Go design rule of avoid import explicitly.
It’s that possible to support implementation of interface implicitly recursively?

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