切片字面量的评估顺序

huangapple go评论78阅读模式
英文:

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)

huangapple
  • 本文由 发表于 2015年12月12日 04:35:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/34232126.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定