douyu1990 2019-05-08 10:57
浏览 486
已采纳

在go中使用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.

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?

  • 写回答

1条回答 默认 最新

  • dongyong3590 2019-05-08 11:08
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度