Program execution
A complete program is created by linking a single, unimported package called the
mainpackage with all the packages it imports, transitively. The main package must have package namemainand declare a functionmainthat takes no arguments and returns no value.func main() { … }Program execution begins by initializing the program and then invoking the function
mainin 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
mainpackages. You can have multiple files in your one and onlymainpackage. And you can have multiplemainpackages in a project, but then each suchmainpackage constitutes the entry point for a new program. - You cannot import
mainTry it. I dare you! - Even your tests use
mainwith 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 automaticmainpackage 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)