Here is an example of the idea I want to demonstrate.
package main
import "fmt"
// interface declaration
//
type A interface {
AAA() string
}
type B interface{
Get() A
}
// implementation
//
type CA struct {}
// implementation of A.AAA
func (ca *CA) AAA() string {
return "it's CA"
}
type C struct {}
// implementation of B.Get, except for returning a 'struct' instead of an 'interface'
func (c *C) Get() *CA {
return &CA{}
}
func main() {
var c interface{} = &C{}
d := c.(B)
fmt.Println(d.Get().AAA())
fmt.Println("Hello, playground")
}
In this example
- interface
B
has a methodGet
to return an interfaceA
- struct
C
has a member functionGet
to return a pointer to structCA
, which implements interfaceA
The result is Go can't deduce interface B
from struct C
, even their Get
method is only different in returning type, which is convertible.
The reason I raise this question is when interface A, B and struct C, CA are in different packages, I can only:
- refine the Get method of
C
to func Get() A, which introduce some dependency between packages. - refine both
Get
method of interfaceB
and structC
to func Get() interface{}
I want to avoid dependency between packages and try not to rely on interface{}, can anyone give me some hint? What's the best practice in Go?