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

1

19

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?

Knopp answered 8/5, 2019 at 10:57 Comment(0)
M
27

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

Monogamy answered 8/5, 2019 at 11:8 Comment(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.Knopp
@NeoLi If you don't have global variables, you don't have to call Init() functions. Try to get rid of global variables.Monogamy
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.Incompressible

© 2022 - 2024 — McMap. All rights reserved.