在go中使用init真的不好吗? [英] Is it really bad to use init in go?

查看:53
本文介绍了在go中使用init真的不好吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

几天前,我开始了一个新的go项目,并使用golangci-lint使我的代码风格良好.我发现gochecknoinits是golangci-lint的短毛绒之一,它告诉我不要使用init.

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.

我认为,为方便起见,我可以将简单的初始代码放在init中.如果没有init,则必须编写一个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.

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

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

推荐答案

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函数

这篇关于在go中使用init真的不好吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆