I stumbled upon what I found to be surprising behavior when sending from one channel directly to another channel:
package main
import (
"fmt"
)
func main() {
my_chan := make(chan string)
chan_of_chans := make(chan chan string)
go func() {
my_chan <- "Hello"
}()
go func() {
chan_of_chans <- my_chan
}()
fmt.Println(<- <- chan_of_chans)
}
Go Playground
I expected <- my_chan to send "Hello" type string. However, it sends type chan string and my code runs fine. This means that what is being (string or chan string) sent depends on the type of the receiver.
I tried naive googling, but since I am not familiar with proper terminology I came up with nothing. Is there a proper term associated with the above behavior? Any additional insight is great of course.
I'm not 100% sure I understand the question, but let's give it a shot.
Consider this line:
chan_of_chans <- my_chan
What you're actually doing is pushing my_chan into the channel, rather than removing something from my_chan and pushing it into chan_of_chans.
If you want to extract something from my_chan and send it to another channel, you need to extract it by using the <- operator right before the channel without a space:
value := <-my_chan
other_chan <- value
Alternatively, this should work:
other_chan <- (<-my_chan)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With