dounao2829 2017-07-24 10:44
浏览 1115
已采纳

golang在一个包中允许多个init的目的是什么?

I know that golang allows multiple init in one package and even in one file. I am wondering why? For example, if a pkg has many files, we could write multiple init then we could get lost in where to we should put init, and we could be also confused about the init order if we have multiple init in one pkg. (I mean is this better? we can only have 1 init, then we can have some initXXX, then put them into init, it seems quite clean.) What's the advantage of doing this in code struct view?

  • 写回答

2条回答 默认 最新

  • drygauost253590142 2017-07-24 10:54
    关注

    This question may be somewhat opinion based, but using multiple package init() functions can make your code easier to read and maintain.

    If your source files are large, usually you arrange their content (e.g. types, variable declarations, methods etc.) in some logical order. Allowance of multiple init() functions give you the possibility to put initialization code near to the parts they ought to initialize. If this would not be allowed, you would be forced to use a single init() function per package, and put everything in it, far from the variables they need to initialize.

    Yes, having multiple init() functions may require some care regarding the execution order, but know that using multiple init() functions is not a requirement, it's just a possibility. And you can write init() functions to not have "side" effects, to not rely on the completion of other init() functions.

    If that is unavoidable, you can create one "master" init() which explicitly controls the order of other, "child" init() functions.

    An example of a "master" init() controlling other initialization functions:

    func init() {
        initA()
        initB()
    }
    
    func initA() {}
    func initB() {}
    

    In the above example, initA() will always run before initB().

    Relevant section from spec: Package initialization.

    Also see related question: What does lexical file name order mean?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题