Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending directly from one channel to another

Tags:

go

channel

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.

like image 874
Akavall Avatar asked Dec 10 '22 17:12

Akavall


1 Answers

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)
like image 150
robbrit Avatar answered Jan 05 '23 23:01

robbrit