首页  >  文章  >  后端开发  >  如何将一个接口的切片传递给需要 Go 中不同的兼容接口切片的函数?

如何将一个接口的切片传递给需要 Go 中不同的兼容接口切片的函数?

Susan Sarandon
Susan Sarandon原创
2024-10-24 20:53:17457浏览

How to Pass a Slice of One Interface to a Function Expecting a Slice of a Different, Compatible Interface in Go?

将接口切片传递给 Go 中的不同兼容接口

在 Go 中使用接口时,您可能会遇到需要的情况将一个接口的切片传递给需要不同接口切片的函数,尽管第一个接口包括第二个接口。

考虑以下示例:

<code class="go">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
}

func single(r io.Reader) {
    fmt.Println("in single")
}

func slice(r []io.Reader) {
    fmt.Println("in slice")
}

im := &Impl{}
single(im) // works
list := []A{im}
slice(list) // fails: cannot use list (type []A) as type []io.Reader</code>

在传递将 A 类型的单个项传递给带有接口参数 io.Reader 的函数 single 会成功,尝试将 A 的切片传递给需要 io.Reader 切片的函数切片会失败。

解决方案:

不幸的是,这个问题是 Go 中的限制。要解决此问题,您必须创建所需界面类型的新切片,并使用现有切片中的元素填充它。

<code class="go">newList := make([]io.Reader, len(list))
for i, elem := range list {
    newList[i] = elem
}

slice(newList) // now works</code>

以上是如何将一个接口的切片传递给需要 Go 中不同的兼容接口切片的函数?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn