直接从一个频道发送到另一个频道 [英] Sending directly from one channel to another

查看:55
本文介绍了直接从一个频道发送到另一个频道的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我偶然发现了从一个频道直接发送到另一频道时令人惊讶的行为:

 程序包主要进口 ("fmt")func main(){my_chan:= make(chan字符串)chan_of_chans:= make(chan chan字符串)转到func(){my_chan<-你好"}()转到func(){chan_of_chans<-my_chan}()fmt.Println(<-<-chan_of_chans)} 

去游乐场

我希望<-my_chan 发送"Hello" 类型为 string .但是,它发送类型为 chan string 的代码,并且我的代码运行良好.这意味着要发送的内容( string chan string )取决于接收器的类型.

我尝试过幼稚的谷歌搜索,但是由于我对适当的术语不熟悉,因此我一无所获.是否有与上述行为相关的适当术语?当然,任何其他见解都是很棒的.

解决方案

我不是100%肯定我理解这个问题,但是让我们尝试一下.

考虑这一行:

  chan_of_chans<-my_chan 

您实际上正在做的是将 my_chan 推送到频道中,而不是从 my_chan 中删除某些内容并将其推送到 chan_of_chans 中./p>

如果您想从 my_chan 中提取某些内容并将其发送到另一个频道,则需要使用<-运算符来提取该内容,而不要在该频道之前空格:

  value:=< -my_chanother_chan<-值 

或者,这应该可以工作:

  other_chan<-(< -my_chan) 

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)

这篇关于直接从一个频道发送到另一个频道的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆