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

Susan Sarandon
Release: 2024-10-26 16:27:02
Original
273 people have browsed it

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

Type Conversion of Slices Containing Different Interfaces

In Go, it is possible to encounter a scenario where you need to pass a slice of one interface to a function that expects a slice of a different compatible interface. Consider the following example:

<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>
Copy after login

Interface Compatibility

In this example, interface A includes interface B, i.e., every type that implements A also implements B. As a result, a concrete implementation of A, such as Impl, satisfies both A and B.

Passing Individual Values

If we attempt to pass individual items across functions, it funktioniert as expected:

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

Passing Slices

However, when trying to pass slices, we encounter an error:

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

The error is: cannot use list (type []A) as type []io.Reader in argument to slice

Solution

To resolve this issue, we can manually create a new slice of the desired interface type:

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

slice(ioReaders) // now works</code>
Copy after login

The above is the detailed content of How to Convert a Slice of One Interface Type to Another in Go?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!