Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

goroutine channels - the value of send statement

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

like image 827
platypus Avatar asked Feb 20 '23 19:02

platypus


1 Answers

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.

like image 67
Sonia Avatar answered Feb 26 '23 20:02

Sonia