问题
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:
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)
来源:https://stackoverflow.com/questions/34232126/order-of-evaluation-in-a-slice-literal