且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在go中使用init真的不好吗?

更新时间:2023-02-11 08:52:53

init()函数是一种方便的工具,有时是必需的,但不应过度使用.它们通常用于初始化某些全局变量,但甚至应尽可能避免使用全局变量.

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.

github.com/leighmcculloch/gochecknoinits :

init函数导致导入具有副作用,并且副作用难以测试,降低了可读性并增加了代码的复杂性.

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.

有您的答案.导入软件包时,将调用其 init()函数,并且可以执行它们想要执行的任何操作.它们可能会更改某些(不相关的)测试所依赖的内容,因此测试是否通过可能取决于您是否导入特定的程序包.

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.

进一步阅读:转到:没有全局变量,没有init函数