为什么不能在Go中将函数命名为”init”?

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

Why can't you name a function in Go "init"?

问题

所以,今天在编码时,我发现创建一个名为init的函数会生成一个错误method init() not found,但是当我将其重命名为startup时,一切都正常工作。

在Go语言中,是否保留了“init”这个词用于某些内部操作,还是我漏掉了什么?

英文:

So, today while I was coding I found out that creating a function with the name init generated an error method init() not found, but when I renamed it to startup it all worked fine.

Is the word "init" preserved for some internal operation in Go or am I'm missing something here?

答案1

得分: 19

是的,函数init()是特殊的。它在包被加载时自动执行。即使main包中也可以包含一个或多个在实际程序开始之前执行的init()函数:http://golang.org/doc/effective_go.html#init

它是包初始化的一部分,如语言规范所解释的:http://golang.org/ref/spec#Package_initialization

它通常用于初始化包变量等。

英文:

Yes, the function init() is special. It is automatically executed when a package is loaded. Even the package main may contain one or more init() functions that are executed before the actual program begins: http://golang.org/doc/effective_go.html#init

It is part of the package initialization, as explained in the language specification: http://golang.org/ref/spec#Package_initialization

It is commonly used to initialize package variables, etc.

答案2

得分: 11

你可以在使用init时遇到的不同错误中查看golang/test/init.go中的代码。

// 验证对init的错误使用是否被检测到。
// 无法编译通过。

package main

import "runtime"

func init() {
}

func main() {
    init() // ERROR "undefined.*init"
    runtime.init() // ERROR "unexported.*runtime\.init"
    var _ = init // ERROR "undefined.*init"
}

init本身由golang/cmd/gc/init.c管理,现在在cmd/compile/internal/gc/init.go中:

/*
* 名为init的函数是一个特例。
* 它在main运行之前被初始化调用。为了使其在包内唯一且不可调用,通常的名称“pkg.init”被改为“pkg.init·1”。
*/

它的使用在“When is the init() function in go (golang) run?”中有说明。

英文:

You can also see the different errors you can get when using init in golang/test/init.go

// Verify that erroneous use of init is detected.
// Does not compile.

package main

import "runtime"

func init() {
}

func main() {
    init() // ERROR "undefined.*init"
    runtime.init() // ERROR "unexported.*runtime\.init"
    var _ = init // ERROR "undefined.*init"
}

init itself is managed by golang/cmd/gc/init.c:
Now in cmd/compile/internal/gc/init.go:

/*
* a function named init is a special case.
* it is called by the initialization before
* main is run. to make it unique within a
* package and also uncallable, the name,
* normally "pkg.init", is altered to "pkg.init·1".
*/

Its use is illustrated in "When is the init() function in go (golang) run?"

huangapple
  • 本文由 发表于 2014年9月6日 19:32:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/25699791.html
匿名

发表评论

匿名网友

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

确定