Home >Backend Development >Golang >## 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!