gogolangci-lint

Is it really bad to use init() functions in Go?


I started a new go projects a few days ago, and I use golangci-lint to make my code in good style. I found gochecknoinits is one of linters of golangci-lint, and it tells me not to use init.

In my opinion, I can put simple initial code in init for convenience. Without init, I must write a Init function and find somewhere to call it before use that package. This can be forgotten or be done multiple times.

So, is it really bad to use init in go?


Solution

  • Package init() functions are a handy tool, sometimes necessary, but should not be overused. They are often used to initialize some global variables, but even global variables should be avoided as much as possible.

    Quote from github.com/leighmcculloch/gochecknoinits:

    Init functions cause an import to have a side effects, and side effects are hard to test, reduce readability and increase the complexity of code.

    There is your answer. When you import a package, its init() functions are called and may do whatever they want to. They may change things some of your (unrelated) tests depend on, so whether your tests pass could depend on whether you import a specific package.

    Further reading: Go: No globals, no init functions