首页  >  文章  >  后端开发  >  ## Go 中如何将接口分片转换为兼容的接口分片?

## Go 中如何将接口分片转换为兼容的接口分片?

Mary-Kate Olsen
Mary-Kate Olsen原创
2024-10-24 18:28:55766浏览

## How to Convert a Slice of Interfaces to a Compatible Interface Slice in Go?

将接口切片转换为兼容的接口切片

实现包含重叠方法的不同接口可以提供编程灵活性。但是,将一个接口的一部分传递给需要不同但兼容的接口的函数可能会导致错误。让我们探讨如何在 Go 中解决这个问题。

假设我们有接口 A 和 B,其中 A 包含 B。A 的实现 Impl 满足 A 和 B。

<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
}</code>

单个项目可以轻松地跨函数传递。但是,尝试将 A 的切片传递给需要 io.Reader 的函数可能会失败。

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

要解决此问题,我们可以创建一个 []io.Reader 类型的新切片,并用 [ 中的元素填充它。 ]一个。这是绕过限制并确保不同但重叠的接口类型之间的兼容性的解决方法。

以上是## Go 中如何将接口分片转换为兼容的接口分片?的详细内容。更多信息请关注PHP中文网其他相关文章!

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