mnemotronic
mnemotronic

Reputation: 1026

Package "main" and func "main"

The intro/sample go progs I've seen and experimented with start with

package main

and have

func main()

Is there any relationship between the "main" in the package line and the "main" in the func line? I'm guessing not. C/C++ uses the same "main" entry point. Just want to make sure though. I haven't seen any docs that say the use of "main" is just a coincidence.

Upvotes: 50

Views: 33626

Answers (1)

Thundercat
Thundercat

Reputation: 120941

The entry point for the application is the main function in the main package as described in the specification:

A complete program is created by linking a single, unimported package called the main package with all the packages it imports, transitively. The main package must have package name main and declare a function main that takes no arguments and returns no value.

func main() { … }

Program execution begins by initializing the main package and then invoking the function main. When that function invocation returns, the program exits. It does not wait for other (non-main) goroutines to complete.

The language specification does not give special meaning to the name main outside of this context. The name main is not a reserved name.

It's OK to declare a main function in non-main packages. In such cases, it's just a function named main.

Upvotes: 60

Related Questions