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.
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.
Your first program. The first statement in a Go source file must be package name . Executable commands must always use package main .
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.
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.
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 functionmain
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With