我有两个界面,A
和B
。 A
包含B
的情况恰好发生。最后,我有一个A
(称之为Impl
)的具体实现,根据定义,它也实现了B
。
例如:
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
}
由于A
需要Read()
,Impl
需要A
,所以它也会满足io.Reader
。
如果我尝试跨功能传递单个项目,它可以正常工作。但是,如果我尝试将A
切片到期望io.Reader
的函数,则会失败。
示例:
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)
如果我可以将A
传递给single(r io.Reader)
,为什么我不能将[]A
传递给slice(r []io.Reader)
,我该如何更正呢?
https://play.golang.org/p/QOREQJTQhD的实际实施只是取消注释main()
中的最后两行,错误显示:
main.go:38: cannot use list (type []A) as type []io.Reader in argument to slice
答案 0 :(得分:1)
我在这里问过类似的东西 In Go, how can I make a generic function with slices?
可悲的是,这绝对是Go的弱点。解决这个问题的唯一方法是使用[] A
中的元素创建一个类型为[] io.Reader的新切片。