doufei2194 2013-05-31 19:40
浏览 27
已采纳

表达式求值顺序

I was curious about the order in which some various types of expressions, so I tried this code in the top declaration level, thinking it would fail, but found that it works:

http://play.golang.org/p/CfP3DEC5LP

var x = func() *Foo {
    fmt.Println(f) // prints &{foobar}
    return f
}()

var f = &Foo{"foobar"}

type Foo struct {
    bar string
}

Please note:

  • the type Foo struct declaration is at the bottom

  • before the type declaration there's a var f declaration and &Foo{] assignment

  • before the var declaration, there's a function that's invoked immediately, which references and returns the f variable.

While it didn't surprise me too much that I could make a &Foo{} value even though it took place before the type Foo struct declaration, it did surprise me that I could successfully reference and print the f value before its assignment.

Is this a reliable and specified behavior? I couldn't find any reference to such an ordering in the specification, but perhaps I overlooked it.

  • 写回答

1条回答 默认 最新

  • dqqt31923 2013-05-31 19:49
    关注

    See the Go programming language reference

    Within a package, package-level variables are initialized, and constant values are determined, according to order of reference: if the initializer of A depends on B, A will be set after B. Dependency analysis does not depend on the actual values of the items being initialized, only on their appearance in the source. A depends on B if the value of A contains a mention of B, contains a value whose initializer mentions B, or mentions a function that mentions B, recursively. It is an error if such dependencies form a cycle. If two items are not interdependent, they will be initialized in the order they appear in the source, possibly in multiple files, as presented to the compiler. Since the dependency analysis is done per package, it can produce unspecified results if A's initializer calls a function defined in another package that refers to B.

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

报告相同问题?

悬赏问题

  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 AT89C51控制8位八段数码管显示时钟。
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题