Home  >  Article  >  Backend Development  >  How to Convert a Slice of One Interface Type to Another in Go?

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

Susan Sarandon
Susan SarandonOriginal
2024-10-26 16:27:02263browse

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>

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>

Passing Slices

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

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

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>

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!

Statement:
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