表达式求值顺序

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.

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.