Home >Backend Development >Golang >How to Pass a Slice of One Interface to a Function Expecting a Slice of a Different, Compatible Interface in Go?
Passing a Slice of Interface to a Different Compatible Interface in Go
When working with interfaces in Go, you may encounter situations where you need to pass a slice of one interface to a function that expects a slice of a different interface, despite the first interface including the second.
Consider the following example:
<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 } func single(r io.Reader) { fmt.Println("in single") } func slice(r []io.Reader) { fmt.Println("in slice") } im := &Impl{} single(im) // works list := []A{im} slice(list) // fails: cannot use list (type []A) as type []io.Reader</code>
While passing an individual item of type A to the function single with an interface parameter io.Reader succeeds, attempting to pass a slice of A to the function slice expecting a slice of io.Reader fails.
Resolution:
Unfortunately, this issue is a limitation in Go. To work around it, you must create a new slice of the desired interface type and populate it with elements from the existing slice.
<code class="go">newList := make([]io.Reader, len(list)) for i, elem := range list { newList[i] = elem } slice(newList) // now works</code>
The above is the detailed content of How to Pass a Slice of One Interface to a Function Expecting a Slice of a Different, Compatible Interface in Go?. For more information, please follow other related articles on the PHP Chinese website!