When I tried to print out:
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
}
}
}
Thank you
It's true, c <- x
is a statement and has no value.
You may be confusing select
with switch
. Switch works by seeing which case expression matches or evaluates to true. Select, on the other hand, looks for cases which are not blocking, picks one of them to allow to proceed, and then runs the statements in the case block.
So no, c <- x
is not evaluated to true wen the sending operation is successful. Instead, the statement of the case block, x, y = y, x + y
is simply executed. There is no result of a send, no true value, stored anywhere.
You may have read that for a receive operation, a variable assigned with a short declarion is only in the scope of the case block. This is true (although there are no short declarations in the cases of the select statement above.) If you had a case where you wanted a received value after the case block ends, you would use a simple assignment and not a short declaration.
Oblig: the language spec on the select statement. It's really very readable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With