The init() function

Every Go package can optionally have a function named init() that is automatically executed at the beginning of the execution time.

The init() function is a private function by design, which means that it cannot be called from outside the package in which it is contained. Additionally, as the user of a package has no control over the init() function, you should think carefully before using an init() function in public packages.

I will now present a code example with multiple init() functions from multiple Go packages. Examine the code of the following basic Go package, which is simply called a:

package a 
 
import ( 
   "fmt" 
) 
 
func init() { 
   fmt.Println("init() a") 
} 
 
func FromA() { 
   fmt.Println("fromA()") 
} 

The a package implements an init() function and a public one named FromA().

After that, you will need to execute the following commands from your Unix shell so that the package becomes available to the current Unix user:

$ mkdir ~/go/src/a
$ cp a.go ~/go/src/a/
$ go install a

Now, look at the code of the next Go code package, which is named b:

package b 
 
import ( 
   "a" 
   "fmt" 
) 
 
func init() { 
   fmt.Println("init() b") 
} 
 
func FromB() { 
   fmt.Println("fromB()") 
   a.FromA() 
} 

What is happening here? Package a uses the fmt standard Go package. However, package b needs to import package a as it uses a.FromA(). Both a and b have an init() function.

As before, you will need to install that package and make it available to the current Unix user by executing the following commands from your Unix shell:

$ mkdir ~/go/src/b
$ cp b.go ~/go/src/b
$ go install b

Thus, we currently have two Go packages that both have an init() function. Now try to guess the output that you will get from executing manyInit.go, which has the following code:

package main 
 
import ( 
   "a" 
   "b" 
   "fmt" 
) 
 
func init() { 
   fmt.Println("init() manyInit") 
} 
 
func main() { 
   a.FromA() 
   b.FromB() 
} 

The actual question could have been: How many times is the init() function of package a going to be executed? Executing manyInit.go will generate the following output and shed some light on this question:

$ go run manyInit.go
init() a
init() b
init() manyInit
fromA()
fromB()
fromA()

The preceding output shows that the init() function of a was executed only once, despite the fact that the a package is imported two times by two different packages. Additionally, as the import block from manyInit.go is executed first, the init() function of package a and package b are executed before the init() function of manyInit.go, which makes perfect sense. The main reason for this is that the init() function of manyInit.go is allowed to use an element from either a or b.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.194.57