How to Pass Slices of Compatible Interfaces in Go?

Mary-Kate Olsen
Release: 2024-10-25 06:01:02
Original
507 people have browsed it

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

}

type B interface {

Read(b []byte) (int, error)
Copy after login

}
`

Concretely, the Impl struct implements both interfaces:

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

return 10, nil
Copy after login

}
func (I Impl) Close() error {

return nil
Copy after login

}
`

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

`
func single(r io.Reader) {

fmt.Println("in single")
Copy after login

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

fmt.Println("in slice")
Copy after login

}

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

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

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!