g6vuqq
Last Updated: February 25, 2016
·
4.03K
· hoffoo
9582a1e999527bea2c2fa342dceb03d0

Go's init function

go

The init function is a special function in go. Each source file can have
an init function, or even multiple init functions. They will be
evaluated right before execution - meaning that after all variables have
been initialized. Go initializes in the following order:

imported packages -> local variables -> init function(s) -> main

This means that by the time init runs variables which rely on imported
code will be usable. It can be used to verify program state or do some
kind of bootstrapping for a library.

This can be seen in the go image package, where different formats are
imported for their side effects. Typical import looks like this:

// This is all you need to Decode gif and jpeg images
import (
    "image"
    _ "image/gif"
    _ "image/jpeg"
)

This is done with the init function. The image package has a
RegisterFormat function that's it to keep state of what its capable
of Decoding/Encoding. In image/gif the init function registers its
format, including how to detect a gif and how to decode it.

Third party libraries can take advantage of this - for example
go's webp lib also registers its codec in an init function, using it is
just like using a standard library format.

Some resources:

http://golang.org/doc/effective_go.html#init
http://code.google.com/p/go/source/browse/src/pkg/image/format.go?name=release

Edit: example init function

func init() {}
Say Thanks
Respond