doutian4046 2015-12-11 20:35
浏览 32
已采纳

Golang评估顺序

I recently went through Golang'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?

Thanks in advance.

  • 写回答

1条回答 默认 最新

  • doubi8965 2015-12-11 20:45
    关注

    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)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 武汉岩海低应变分析软件,导数据库里不显示波形图
  • ¥15 CreateBitmapFromWicBitmap内存释放问题。
  • ¥30 win c++ socket
  • ¥15 CanMv K210开发板实现功能
  • ¥15 C# datagridview 栏位进度
  • ¥15 vue3页面el-table页面数据过多
  • ¥100 vue3中融入gRPC-web
  • ¥15 kali环境运行volatility分析android内存文件,缺profile
  • ¥15 写uniapp时遇到的问题
  • ¥15 vs 2008 安装遇到问题