2

Suppose I have an array of items that implement an interface Reader:

var items []Foo

How would I pass these items into a function that takes readers?

func (items []Reader) { ... }

I can't use the type []Reader because I get an error like:

Cannot use type `[]Foo` as type `[]Reader`...
1

2 Answers 2

2

For example,

package main

import (
    "bytes"
    "io"
)

var items []*bytes.Buffer

func f(items []io.Reader) {}

func main() {
    readers := make([]io.Reader, len(items))
    for i, item := range items {
        readers[i] = item
    }
    f(readers)
}
Sign up to request clarification or add additional context in comments.

2 Comments

That works, but it means I have to loop over all the items before I call the function. I was trying to avoid the loop.
@VladtheImpala: Because they do not have the same representation in memory, it is necessary to copy the elements individually. Can I convert a []T to an []interface{}?
1

Similar to peterSO's answer.

package main

import (
    "bytes"
    "io"
)

type Foo struct{}
type Foos []Foo


func (f Foos) toReaders() []io.Reader {
    readers := make([]io.Reader, len(f))
    for i, item := range f {
        readers[i] = item
    }
    return  readers
}

func f(items []io.Reader) {}

func main() {
    var x Foos
    f(x.toReaders())
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.