Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/go/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Go中,何时在多值赋值中复制值?_Go_Return_Variable Assignment_Specifications - Fatal编程技术网

在Go中,何时在多值赋值中复制值?

在Go中,何时在多值赋值中复制值?,go,return,variable-assignment,specifications,Go,Return,Variable Assignment,Specifications,考虑使用Go 1.8评估的以下Go功能: 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 } 如注释中所述,函

考虑使用Go 1.8评估的以下Go功能:

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
}
如注释中所述,函数似乎总是在c生成值后复制i。由于这是在遇到return语句~1s后发生的,这不是我所期望的

如果返回中的值顺序颠倒,并且返回被赋值替换,则行为相同

请注意,我并不是说这种行为是错误的——只是出乎意料。事实上,这几乎总是你想要发生的事情

因此,问题是这种预期/指定的行为是否可以依赖


在这种情况下,上的spec部分没有确切说明它何时阻塞线程。

根据上的spec部分,类似于这样的语句中的函数和接收操作从左到右进行计算:

例如,在函数“局部赋值”中

y[f()], ok = g(h(), i()+x[j()], <-c), k()
因此,尽管行为符合要求,但不幸的是,它没有具体说明,也无法依赖

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