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 bottombefore the
type
declaration there's avar f
declaration and&Foo{]
assignmentbefore the
var
declaration, there's a function that's invoked immediately, which references and returns thef
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.