This question already has an answer here:
- Type converting slices of interfaces 5 answers
I have two interfaces, A
and B
. It happens that A
includes B
. Finally, I have a concrete implementation of A
(call it Impl
), which, by definition, also implements B
.
For example:
type A interface {
Close() error
Read(b []byte) (int, error)
}
type Impl struct {}
func (I Impl) Read(b []byte) (int, error) {
fmt.Println("In read!")
return 10, nil
}
func (I Impl) Close() error {
fmt.Println("I am here!")
return nil
}
Since A
requires Read()
, and Impl
implements A
, it also satisfies io.Reader
.
If I try to pass individual items across functions, it works fine. But if I try slices of A
to functions expecting io.Reader
, it fails.
Example:
func single(r io.Reader) {
fmt.Println("in single")
}
func slice(r []io.Reader) {
fmt.Println("in slice")
}
im := &Impl{}
// works
single(im)
// FAILS!
list := []A{t}
slice(list)
If I can pass an A
to single(r io.Reader)
, why can I not pass []A
to slice(r []io.Reader)
, and how would I correct it?
Actual implementation at https://play.golang.org/p/QOREQJTQhD just uncomment the last two lines in main()
and the error shows:
main.go:38: cannot use list (type []A) as type []io.Reader in argument to slice
</div>