Understanding <- <-in
For newcomers to Golang (like myself) seeing c <- <-chan
can be quite confusing. It isn't that channels in and of themselves are confusing, but the seemingly duplicate <-
is deceptive. So I broke it down a bit and it really is simple. See this example in a simple channel fanning function.
func fanIn(input1, input2 <-chan string) <-chan string {
c := make(chan string)
// This looks confusing, but is actually simple.
// This is easier to digest if we read from right to left.
// On the right hand side we have a channel (input1).
// When that channel gets data (<-input1), pass that data
// to the new channel (c <-). So at run time we essentially have
// c <- "my value"
go func() {
for {
c <- <-input1
}
}()
go func() {
for {
c <- <-input2
}
}()
return c
}
Read more about concurrency here- http://blog.golang.org/pipelines
Written by Brandon Hansen
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Golang
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#