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

So, today, when I was in encoding, it turned out that creating a function called init caused a method init() not found error, but when I renamed it to startup , everything was fine.

Is the word "init" saved for some internal operation in Go or am, am I missing something here?

+11
go naming internal
source share
2 answers

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

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

It is usually used to initialize package variables, etc.

+18
source share

You can also see various errors you may get when using init in golang/test/init.go
Now cmd/compile/internal/gc/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 controlled by golang/cmd/gc/init.c :

 /* * 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 does the init() function run in go (golang)? "

+9
source share

All Articles