Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Package "main" and func "main"

Tags:

go

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.

like image 734
mnemotronic Avatar asked Feb 19 '17 22:02

mnemotronic


People also ask

What does package main mean?

Package Main The package “main” tells the Go compiler that the package should compile as an executable program instead of a shared library. The main function in the package “main” will be the entry point of our executable program.

Does go need a main package?

Your first program. The first statement in a Go source file must be package name . Executable commands must always use package main .

Why do we write package main in Golang?

The main package and main() function Go programs start running in the main package. It is a special package that is used with programs that are meant to be executable. By convention, Executable programs (the ones with the main package) are called Commands. Others are called simply Packages.

Can we define two go program with a main method within a package?

You can have multiple main function in go but the package should be declared main. This way you can have multiple go scripts/file inside package main where each file will have main function.


1 Answers

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.

like image 78
Bayta Darell Avatar answered Sep 20 '22 04:09

Bayta Darell