函数变量表示初始化

huangapple go评论82阅读模式
英文:

Function variable representing init

问题

在Go语言中,你可以在一个包中定义多个init函数,所有这些函数都会在执行之前按照未指定的顺序运行。拥有多个这样的函数的一个后果是,在正常的代码中无法调用或识别它们。例如,以下代码将无法编译:

func main() {
    fmt.Println(init)
}
func init() { }

(在这里可以看到一个Go playground的示例)
我的问题是 - 能够拥有多个init函数有什么优势,如果没有多个init函数,我们能否引用或调用init函数?

英文:

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() {
    fmt.Println(init)
}
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 <i>weren't</i> multiple init functions, would we be able to reference or call init functions?

答案1

得分: 1

能够拥有多个init函数的优势在我看来主要是通过局部性提高了可读性:您可以将初始化函数写在被初始化的内容旁边,而不是远离它,如果您必须将所有的init函数集中到一个地方。顺便说一句,这个地方甚至可以是一个不同的源文件。

假设每个包只有一个init函数的函数指针可能也是被禁止的。原因是拥有这样的指针会在某些情况下允许在运行其依赖项(其他包中的其他init函数)之前调用init函数,这将打破某些保证

英文:

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.

huangapple
  • 本文由 发表于 2013年7月19日 17:11:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/17742278.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定