英文:
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?"
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论