英文:
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 (
"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)
}
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
得分: 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 <- 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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论