13

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?

030
  • 10,842
  • 12
  • 78
  • 123
Neo Li
  • 213
  • 1
  • 2
  • 9

1 Answers1

20

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

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
icza
  • 389,944
  • 63
  • 907
  • 827
  • 3
    Thanks for your reply, and I agree with you. It really causes problems to my testing. But I a little hate to call public Init functions, especially when there are many main in my project which means I must call Init in many places. – Neo Li May 08 '19 at 11:24
  • 2
    @NeoLi If you don't have global variables, you don't have to call `Init()` functions. Try to get rid of global variables. – icza May 08 '19 at 11:36
  • I have an example. I load an environment variable in init() and do os.Exit(1) if it is not set. My unit tests fail as this is always executed, being totally unrelated the file under test. – Matthias Sommer Feb 26 '20 at 09:46