Home  >  Article  >  Backend Development  >  How to Pass Slices of Compatible Interfaces in Go?

How to Pass Slices of Compatible Interfaces in Go?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-25 06:01:02500browse

How to Pass Slices of Compatible Interfaces in Go?

Passing Slices of Compatible Interfaces in Go

In Go, you may encounter difficulties when passing slices of one interface to functions expecting slices of a different interface, even if the former includes the latter. To illustrate this issue, consider two interfaces, A and B, where A includes B.

`
type A interface {

Close() error
Read(b []byte) (int, error)

}

type B interface {

Read(b []byte) (int, error)

}
`

Concretely, the Impl struct implements both interfaces:

`
type Impl struct {}
func (I Impl) Read(b []byte) (int, error) {

return 10, nil

}
func (I Impl) Close() error {

return nil

}
`

While individual items can be passed across functions without issue, passing slices encounters an error:

`
func single(r io.Reader) {

fmt.Println("in single")

}
func slice(r []io.Reader) {

fmt.Println("in slice")

}

impl := &Impl{}
single(impl) // works

list := []A{impl}
slice(list) // FAILS
`

To resolve this, you must create a new slice of the expected type ([]io.Reader) and populate it with elements from the source slice ([]A):

`
newSlice := make([]io.Reader, len(list))
for i, v := range list {

newSlice[i] = v

}
slice(newSlice)
`

This approach allows you to pass slices of one interface to functions expecting slices of another compatible interface, resolving the error raised when attempting to directly pass the original slice.

The above is the detailed content of How to Pass Slices of Compatible Interfaces 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