Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it really bad to use init in go?

Tags:

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?

like image 731
Neo Li Avatar asked May 08 '19 10:05

Neo Li


People also ask

Does init run before main Golang?

Whenever the init() function is declared in code, Go loads and runs it prior to anything else in the package. A package, however, can have more than one init() function and all of them are executed before the main package's main() function. Also note that the init() function is never called explicitly.

When init is called Golang?

init() Function This function is present in every package and this function is called when the package is initialized. This function is declared implicitly, so you cannot reference it from anywhere and you are allowed to create multiple init() function in the same program and they execute in the order they are created.

Can you define multiple init () functions in the same .Go file?

It is possible to define multiple init() functions in one file and multiple packages with init() functions. init() functions in a single file will be loaded in the order that they have been declared, while init() functions in multiple packages will be loaded based on the file names used in alphabetical order.

When INIT is called?

The init block is always called after the primary constructor. A class file can have one or more init blocks executing in series i.e. one after another.


1 Answers

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

like image 94
icza Avatar answered Sep 21 '22 08:09

icza