Expression Evaluation Order

I was interested to learn about the order in which there are several types of expressions, so I tried this code at the top level of the ad, thinking that 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 } 

Note:

  • The type Foo struct declaration is at the bottom

  • before type declaration there is var f declaration and &Foo{] assignment

  • before the var declaration, there is a function that is called immediately, which refers and returns the variable f .

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

Is this reliable and specific behavior? I could not find any reference to such an order in the specification, but perhaps I did not notice it.

+6
source share
1 answer

See Go Programming Language Link

Variables of the package level are initialized in the package and constant values ​​are determined in accordance with the order of access: if initializer A depends on B, A will be set after B. Dependence analysis does not depend on the actual values ​​of the elements that are initialized, only by their appearance in the source. A depends on B if the value of A contains a reference to B, contains the value that the initializer mentions B or mentions a function that mentions B, recursively. It is a mistake if such dependencies form a loop. If two elements are not interdependent, they will be initialized in the order they appear in the source, possibly in several files, as presented to the compiler. Since dependency analysis is performed for each package, it can generate unspecified results if the initializer calls a function defined in another package that references B.

+10
source

Source: https://habr.com/ru/post/946290/


All Articles