patterngoModerate
Different ways to pass channels as arguments in function
Viewed 0 times
functionwayschannelsdifferentpassarguments
Problem
I was reading some go code and say a few different ways to pass go channels. Maybe they are the same but I was wondering if there is any difference since I couldn't find documentation online:
1)
2)
3)
4)
I was wondering what the difference between them were and if they were just equivalent ways to do the same thing: pass a channel around different goroutines.
NOTE: I am aware that there is no reason to pass a pointer to a chan, map, or slice, or function value, since those are all reference types which internally contain a pointer (the exception would be if you want the callee to change the reference type header). The only reason I provided it is for completeness (i.e. to really provide every way a channel could be attempted to be passed as a parameter and to make on question that hopefully, references all ways to do this and compares them).
1)
func serve(ch <-chan interface{}){ //do stuff }2)
func serve(ch chan<- interface{}){ //do stuff }3)
func serve(ch chan interface{}){ //do stuff }4)
func server(ch *chan interface{}){ //do stuff}I was wondering what the difference between them were and if they were just equivalent ways to do the same thing: pass a channel around different goroutines.
NOTE: I am aware that there is no reason to pass a pointer to a chan, map, or slice, or function value, since those are all reference types which internally contain a pointer (the exception would be if you want the callee to change the reference type header). The only reason I provided it is for completeness (i.e. to really provide every way a channel could be attempted to be passed as a parameter and to make on question that hopefully, references all ways to do this and compares them).
Solution
These are different types of channels. See http://golang.org/ref/spec#Channel_types . For the pointer stuff: Uncommon, but might be useful if you want to change the channel from inside the function (never saw that in the wild).
Context
Stack Overflow Q#24868859, score: 42
Revisions (0)
No revisions yet.