2013-07-19 09:11
浏览 19


In Go, you can define multiple init functions in a given package, all of which will be run prior to execution in unspecified order. One consequence of having multiples of such functions is that it's impossible to call or identify them in normal code. For example, the following will not compile:

func main() {
func init() { }

(see here for a Go playground example) My question is - what advantage does being able to have multiple init functions give, and if there weren't multiple init functions, would we be able to reference or call init functions?

图片转代码服务由CSDN问答提供 功能建议

在Go中,您可以在给定的包中定义多个 init 函数,所有这些函数 将在执行之前以未指定的顺序运行。 具有多个此类函数的结果之一是,不可能在普通代码中调用或识别它们。 例如,以下内容将不会编译:

  func main(){
func init(){} 

(有关转到游乐场的示例,请参见此处 } 我的问题是-能够拥有多个初始化函数有什么优势,如果根本没有多个初始化函数,我们是否可以引用或调用初始化函数?

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

  • 普通网友 2013-07-19 09:41

    Advantage of being able to have multiple init functions is IMO mainly that it improves readability by locality: You can write the initialization function next to the stuff being initialized and not remotely if you would have to centralize all the init functions to one. Which, BTW, could be then even in a different source file.

    Taking a function pointer of the hypothetical per-package-single init function would be probably prohibited as well. The reason is that having such pointer would allow, in some cases, to call the init function "out of order", ie. before running its dependencies - other init functions in other packages. That would break certain guarantees.

    解决 无用
    打赏 举报

相关推荐 更多相似问题