dre75230 2012-04-14 00:57
浏览 41
已采纳

goroutine通道-send语句的值

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

  • 写回答

1条回答 默认 最新

  • dpzjl68484 2012-04-14 03:02
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 vue3+element-plus页面崩溃
  • ¥15 像这种代码要怎么跑起来?
  • ¥15 怎么改成循环输入删除(语言-c语言)
  • ¥15 安卓C读取/dev/fastpipe屏幕像素数据
  • ¥15 pyqt5tools安装失败
  • ¥15 mmdetection
  • ¥15 nginx代理报502的错误
  • ¥100 当AWR1843发送完设置的固定帧后,如何使其再发送第一次的帧
  • ¥15 图示五个参数的模型校正是用什么方法做出来的。如何建立其他模型
  • ¥100 描述一下元器件的基本功能,pcba板的基本原理