dqroktbn005028 2017-07-10 07:28
浏览 43
已采纳

在Go中,何时在多值分配中复制值?

Consider the following Go function (playground), which was evaluated with Go 1.8:

func f() (int, bool) {
  i := 0
  c := make(chan bool)
  go func() {
    time.Sleep(1 * time.Second)
    i = 1
    c <- true
  }()

  // In practice, `i` will always be 0 here.
  return i, <-c // returns 1, true
}

As stated in the comments, the function seem to always copy i after c has yielded a value. As this happens ~1s after encountering the return statement, this is not what I expected.

The behavior is the same if the value order is reversed in the return and also if the return is replaced by assignment.

Note that I'm not claiming this behavior to be wrong - just unexpected. In fact, this will almost always be what you want to happen.

The question therefore is if this intended/specified behavior that can be relied on?

The spec section on the receive operator doesn't state exactly when it blocks the thread in cases like this.

  • 写回答

1条回答 默认 最新

  • dsfs21312 2017-07-10 07:28
    关注

    According to the spec section on order of evaluation, functions and receive operations in a statement like this are evaluated from left to right:

    For example, in the (function-local) assignment

    y[f()], ok = g(h(), i()+x[j()], <-c), k()
    

    the function calls and communication happen in the order f(), h(), i(), j(), <-c, g(), and k(). However, the order of those events compared to the evaluation and indexing of x and the evaluation of y is not specified.

    But as stated in the emphasized sentence, the order of variable evaluation is not specified.

    The section gives another example that makes this even clearer:

    a := 1
    f := func() int { a++; return a }
    x := []int{a, f()}
    // x may be [1, 2] or [2, 2]: evaluation order between a and f() is not specified
    

    So while the behavior is as desired, it is unfortunately not specified and cannot be relied on.

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

报告相同问题?

悬赏问题

  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)
  • ¥20 matlab yalmip kkt 双层优化问题