gpt4 book ai didi

goroutine channels - send 语句的值

转载 作者:IT王子 更新时间:2023-10-29 00:38:12 26 4
gpt4 key购买 nike

当我试图打印出来时:

fmt.Println(c <- x)
right before the for loop in the code block below to see what "c <- x" would evaluate to, it got the error message:

./select.go:7: send statement c <- x used as value; use select for non-blocking send

Is "c <- x" evaluated to true if the sending operation was successful? And why does Go only let you use the value of the send statement (aka value of "c <- x") inside case statements inside a select statement?

    func fibonacci(c, quit chan int) {
x, y := 1, 1

for {
select {
case c <- x:
x, y = y, x + y
case <-quit:
fmt.Println("quit")
return
}
}
}

谢谢

最佳答案

这是真的,c <- x是一个声明,没有任何值(value)。

您可能会感到困惑 selectswitch . Switch 通过查看哪个 case 表达式匹配或求值为真来工作。另一方面,Select 查找未阻塞的 case,选择其中一个允许继续,然后运行 ​​case block 中的语句。

所以不,c <- x在发送操作成功时未评估为真。相反,case block 的语句 x, y = y, x + y被简单地执行。没有发送结果,没有真正的值(value),存储在任何地方。

您可能已经读到,对于接收 操作,分配有简短声明的变量仅在 case block 的范围内。这是真的(尽管在上面的 select 语句的情况下没有短声明。)如果你有一个情况你想要在 case block 结束后接收到值,你会使用一个简单的赋值而不是短声明。

义务:the language spec on the select statement .它真的非常可读。

关于goroutine channels - send 语句的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10150116/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com