Program execution

January 2, 2025

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 name main and declare a function main that takes no arguments and returns no value.

func main() { … }

Program execution begins by initializing the program and then invoking the function main in package main. 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 only main package. And you can have multiple main packages in a project, but then each such main package constitutes the entry point for a new program.
  • You cannot import main Try it. I dare you!
  • Even your tests use main with a main() 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 run go test, the Go toolchain builds an automatic main package with a main() 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)


Share this

Direct to your inbox, daily. I respect your privacy .

Unsure? Browse the archive .

Get daily content like this in your inbox!

Subscribe