将消息直接从一个频道发送到另一个频道

huangapple go评论95阅读模式
英文:

Sending directly from one channel to another

问题

我在直接从一个通道发送到另一个通道时,遇到了一些令人惊讶的行为:

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)
}

我期望 my_chan <- "Hello" 发送类型为 string"Hello"。然而,它发送的是类型为 chan string 的通道,并且我的代码正常运行。这意味着发送的内容(string 还是 chan string)取决于接收者的类型。

我尝试过简单的搜索,但由于我对正确的术语不熟悉,所以没有找到相关信息。是否有与上述行为相关的正确术语?当然,任何额外的见解都是很好的。

英文:

I stumbled upon what I found to be surprising behavior when sending from one channel directly to another channel:

package main

import (
	&quot;fmt&quot;
)

func main() {
	my_chan := make(chan string)
	chan_of_chans := make(chan chan string)

	go func() {
		my_chan &lt;- &quot;Hello&quot;
	}()

	go func() {
		chan_of_chans &lt;- my_chan
	}()

	fmt.Println(&lt;- &lt;- chan_of_chans)
}

Go Playground

I expected &lt;- my_chan to send &quot;Hello&quot; 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

得分: 17

我不确定我完全理解这个问题,但让我试试。

考虑这行代码:

chan_of_chans <- my_chan

实际上你正在将 my_chan 推送到通道中,而不是从 my_chan 中移除某个东西并将其推送到 chan_of_chans 中。

如果你想从 my_chan 中提取某个东西并发送到另一个通道,你需要在通道之前使用 <- 运算符提取它,而不加空格:

value := <-my_chan
other_chan <- value

或者,这样也可以:

other_chan <- (<-my_chan)
英文:

I'm not 100% sure I understand the question, but let's give it a shot.

Consider this line:

chan_of_chans &lt;- 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 &lt;- operator right before the channel without a space:

value := &lt;-my_chan
other_chan &lt;- value

Alternatively, this should work:

other_chan &lt;- (&lt;-my_chan)

huangapple
  • 本文由 发表于 2016年3月13日 11:56:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/35966277.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定