Package initialization
When a package is imported, it goes through a series of initialization sequences before its members are ready to be used. Package-level variables are initialized using dependency analysis that relies on lexical scope resolution, meaning variables are initialized based on their declaration order and their resolved transitive references to each other. For instance, in the following snippet, the resolved variable declaration order in package foo
will be a
, y
, b
, and x
:
package foo var x = a + b(a) var a = 2 var b = func(i int) int {return y * i} var y = 3
Go also makes use of a special function named init
that takes no arguments and returns no result values. It is used to encapsulate custom initialization logic that is invoked when the package is imported. For instance, the following source code shows an init
function used in the resistor
package to initialize function variable Rpi
:
package resistor var Rpi func(float64, float64...