Home  >  Article  >  Backend Development  >  ## How to Convert a Slice of Interfaces to a Compatible Interface Slice in Go?

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

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-24 18:28:55766browse

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

Converting Slices of Interfaces to Compatible Interface Slices

Implementing different interfaces that contain overlapping methods can provide flexibility in programming. However, passing a slice of one interface to a function expecting a different but compatible interface can result in errors. Let's explore how to address this issue in Go.

Suppose we have interfaces A and B, where A includes B. An implementation of A, Impl, satisfies both A and 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>

Individual items can be passed across functions with ease. However, attempting to pass slices of A to functions expecting io.Reader may fail.

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

To resolve this, we can create a new slice of type []io.Reader and populate it with elements from []A. This is the workaround to bypass the limitation and ensure compatibility between different but overlapping interface types.

The above is the detailed content of ## How to Convert a Slice of Interfaces to a Compatible Interface Slice 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