首页  >  文章  >  后端开发  >  如何在 Go 中将一种接口类型的切片转换为另一种接口类型?

如何在 Go 中将一种接口类型的切片转换为另一种接口类型?

Susan Sarandon
Susan Sarandon原创
2024-10-26 16:27:02263浏览

How to Convert a Slice of One Interface Type to Another in Go?

包含不同接口的切片的类型转换

在Go中,有可能会遇到需要传递一个的切片的场景一个函数的接口,该函数需要不同的兼容接口的一部分。考虑以下示例:

<code class="go">type A interface {
    Close() error
    Read(b []byte) (int, error)
}

type B interface {
    Close() error
}

type Impl struct {}

// Implementation of interface A and B
func (I Impl) Close() error {...}
func (I Impl) Read(b []byte) (int, error) {...}</code>

接口兼容性

在此示例中,接口 A 包含接口 B,即实现 A 的每个类型也实现 B。结果,A 的具体实现,例如 Impl,同时满足 A 和 B。

传递单个值

如果我们尝试跨函数传递单个项目,它按预期运行:

<code class="go">im := &Impl{}
single(im) // works</code>

传递切片

但是,当尝试传递切片时,我们遇到错误:

<code class="go">list := []A{t}
slice(list) // FAILS!</code>

错误是:cannot use list (type []A) as type []io.Reader in argument to slice

解决方案

要解决此问题,我们可以手动创建所需接口类型的新切片:

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

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

以上是如何在 Go 中将一种接口类型的切片转换为另一种接口类型?的详细内容。更多信息请关注PHP中文网其他相关文章!

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