Sending directly from one channel to another

自作多情 提交于 2021-02-07 08:42:07

问题


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.


回答1:


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)


来源:https://stackoverflow.com/questions/35966277/sending-directly-from-one-channel-to-another

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!