Last Updated: February 25, 2016
· hoffoo

Go's init function


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/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:


Edit: example init function

func init() {}