Order of evaluation in a slice literal

核能气质少年 提交于 2021-02-09 10:50:34

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!