切片文字中的求值顺序 [英] Order of evaluation in a slice literal
问题描述
我最近浏览了Go的语言规范" https://golang.org/ref/spec#Order_of_evaluation ,但发现评估顺序与本文档中说明的顺序不同.
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.
例如,它说:
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]
}
我发现切片x的值始终为[2,2].我有什么误会吗?
I found the value of slice x is always [2,2]. Is there anything I misunderstand?
推荐答案
顺序未指定"是指由编译器决定,并且不能保证在不同版本的编译器/其他编译器等上相同/其他机器/一天中的其他时间等
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.
这并不意味着每次或崩溃时它都必须有所不同(因为您可能习惯于C语言,其中未定义的行为"通常意味着不好的事情,例如在释放内存后使用指针)
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)
这篇关于切片文字中的求值顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!