Program execution
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 namemain
and declare a functionmain
that takes no arguments and returns no value.func main() { … }
Program execution begins by initializing the program and then invoking the function
main
in packagemain
. When that function invocation returns, the program exits. It does not wait for other (non-main
) goroutines to complete.
Most of us are probably already familiar with this. It’s almost the first thing any Go programmer learns about Go programming: You must have a function called main()
in a package called main
, otherwise your program won’t run!
But there are a number of subtleties and related concepts not directly drawn out here, that I’d like to talk about.
- There can be only one! No program can have multiple
main
packages. You can have multiple files in your one and onlymain
package. And you can have multiplemain
packages in a project, but then each suchmain
package constitutes the entry point for a new program. - You cannot import
main
Try it. I dare you! - Even your tests use
main
with amain()
function Some readers may be thinking “main()
isn’t the only way to run code! I can run code from a test!” But there’s something you may not know: When you rungo test
, the Go toolchain builds an automaticmain
package with amain()
function that executes your tests. So this isn’t actually an exception to the rule.
Quotes from The Go Programming Language Specification Language version go1.23 (June 13, 2024)