英文:
Order of evaluation in a slice literal
问题
最近我阅读了Go语言的“语言规范”https://golang.org/ref/spec#Order_of_evaluation,但发现其中的求值顺序与该文档中所解释的不同。
例如,文档中提到:
a := 1
f := func() int { a++; return a }
x := []int{a, f()} // x可能是[1, 2]或[2, 2]:a和f()之间的求值顺序未指定
然后我尝试了以下代码:
package main
import "fmt"
func main() {
for {
result := evaluate()
if result == 1 {
break
}
}
}
func evaluate() int {
a := 1
f := func() int { a++; return a }
x := []int{a, f()}
fmt.Println(x)
return x[0]
}
我发现切片x的值始终为[2,2]。我是否有什么误解?
英文:
I recently went through Go's "Language Specification" https://golang.org/ref/spec#Order_of_evaluation but found the order of evaluation being different from what it is explained in this document.
For example, it says:
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
Then I tried with this code:
package main
import "fmt"
func main() {
for {
result := evaluate()
if result == 1 {
break
}
}
}
func evaluate() int {
a := 1
f := func() int { a++; return a }
x := []int{a, f()}
fmt.Println(x)
return x[0]
}
I found the value of slice x is always [2,2]. Is there anything I misunderstand?
答案1
得分: 4
“未指定顺序”意味着由编译器决定,不能保证在不同版本的编译器/其他编译器/其他机器/其他时间等情况下保持一致。
这并不意味着每次都必须不同或崩溃(正如你可能在C语言中习惯的那样,‘未定义行为’通常意味着一些不好的事情,例如在释放内存后继续使用指针)。
英文:
Order 'not specified' means that it's up to compiler to decide, and it is not guaranteed to be the same over different versions of a compiler/other compilers etc/other machine/other time of day etc.
It does not mean that it has to be different each time or crash (as you may be accustomed to from C, where 'undefined behaviour' usually meant something bad, for example like using a pointer after freeing memory)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论