jeudi 6 août 2020

Manually cast/decay chan to <-chan

I have a function:

func f(input interface{}) interface{} {
    t := reflect.ChanOf(reflect.BothDir, <type that depends on input>)
    c := reflect.MakeChan(t, ...)

    // ... push things from input into c ...

    return c
}

It creates a channel with an element type that depends on the input. It could be used like this, but I want it to work for any type, not just int:

x := f(1).(<-chan int)

This fails because I have to use reflect.BothDir inside the function (because I'm sending values to it inside f), so the actual type is chan <something>. I only want users of this function to see the receiving end of the channel though. Is there any way to "cast" chan <something> into <-chan <something> before returning it from f? Using a return type of <-chan interface{} is not an option as going from that type to <-chan <something> would require the user of f to create another channel and manually push the values into that, but I want f to be used as a one-liner.





Aucun commentaire:

Enregistrer un commentaire