在Go中,如何将接口的一部分传递给期望有其他兼容接口的一部分的东西? [英] In Go, how do I pass a slice of interface to something that expects slice of a different compatible interface?
问题描述
我有两个接口, A
和 B
.碰巧 A
包括 B
.最后,我有一个 A
的具体实现(称为 Impl
),根据定义,该实现还实现了 B
.
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
.
例如:
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.阅读器
.
Since A
requires Read()
, and Impl
implements A
, it also satisfies io.Reader
.
如果我尝试跨函数传递单个项目,则可以正常工作.但是,如果我尝试将 A
的切片应用于期望 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.
示例:
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)
,我该如何纠正?
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?
https://play.golang.org/p/QOREQJTQhD 上的实际实现方式取消注释 main()
中的最后两行,错误将显示:
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
推荐答案
我在这里问类似的问题在Go中,如何制作通用函数切片?
I kind of asked something similar here In Go, how can I make a generic function with slices?
遗憾的是,这绝对是Go中的一个弱点.解决此问题的唯一方法是使用[] A
Sadly, this is definitely a weakness in Go. The only way for you to go around this is to make a new slice of type []io.Reader with elements from []A
这篇关于在Go中,如何将接口的一部分传递给期望有其他兼容接口的一部分的东西?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!