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

随声附和 提交于 2019-12-05 00:39:53

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.

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?"

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!