Reputation: 9380
Hi have a function accepting chan []byte
(that, since no direction is specified I understand it is bidirectional). The function does not send or receives anything, only looks at number of elements in the channel for stats related purposes.
I want to call this function within a function with following signature:
func foo(fooChannel chan<- []byte)
But when I try to use argument to call the other function I got the error cannot use fooChannel (type <-chan []byte) as type chan []byte in function argument
.
Is there any way to cast fooChannel to chan []byte
?
Since I am only interested in getting some stats, how should I prototype the function to accept any type of channel (so I can get rid even of the "byte" part)? I am only using len
and cap
with channels received as arguments.
Upvotes: 3
Views: 1484
Reputation: 13072
Is there any way to cast fooChannel to chan []byte?
No, sorry. This is probably just in case someone thinks they would like to send on the receiving channel anyway. But, just a little tiny thing, but... No.
The function does not send or receives anything, only looks at number of elements in the channel for stats related purposes. [...] I am only using
len
andcap
with channels received as arguments.
If it doesn't use the channel in any channel-ish way, you could simply pass len(ch)
and cap(ch)
directly as the arguments. If you don't like it for any reason, you can play with reflect
package, which will allow you to call len
and cap
on any type supporting it (array, channel, slice).
This might be a good start:
package main
import (
"fmt"
"reflect"
)
func stats(i interface{}) {
v := reflect.ValueOf(i)
fmt.Printf("%s size: %d/%d\n", v.Kind(), v.Len(), v.Cap())
}
func main() {
ch := make(chan int, 10)
ch <- 1
stats(ch)
}
// Output: chan size: 1/10
http://play.golang.org/p/2ehYvEmDkS
Upvotes: 1
Reputation: 42431
Rephrased a bit:
"Is there a way to cast a directed channel to an undirected?" No there isn't.
"Is there a notion of 'arbitrary channel' (without element type) in Go?" No there isn't. Go has no generics.
You'll have to write several functions.
Upvotes: 1