Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't you name a function in 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?

like image 503
Max Avatar asked Sep 06 '14 11:09

Max


1 Answers

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

like image 126
VonC Avatar answered Sep 28 '22 23:09

VonC