Go's Entry Point: The `main` Package and Function
A Go program's entry point is `package main`. The compiler finds this package and its `main()` function to create a runnable binary. The footgun is naming a library `main`; this name is reserved for executables and will cause build confusion.
WHY IT EXISTS Go needs a clear, unambiguous signal to distinguish between code meant to be run as a program and code meant to be used as a library. The package main convention solves this by telling the Go compiler, "start here" and "build an executable file."
THE MENTAL MODEL Think of package main as the ignition switch for a Go program. A car has one specific place to turn the key to start the engine. Similarly, a Go executable has exactly one main package with one main function where execution begins. All other packages are parts of the engine, but main is what turns it on.
HOW IT WORKS When you execute go build or go run, the Go toolchain scans the source files. If it finds package main, it knows its job is to produce a single, executable binary. It compiles the main package and all the packages it imports, linking them together. Program execution starts by calling the func main(), which must be defined with no arguments and no return values. If the package is not named main, the toolchain treats it as a library, compiling it into an archive file that can be used by other programs but cannot be run on its own.
WHEN TO USE IT Always use package main for the root package of any standalone application. This applies to command-line tools, web servers, background services, or any program that needs to be executed directly. It is the non-negotiable starting point for your application's logic.
WHEN NOT TO USE IT Do not use package main for code intended to be a reusable library. If you are writing a package that provides utility functions, data structures, or an API for other Go programs to import and use, give it a descriptive name like package cache or package jsonutil. A project can only have one main package that gets compiled into the final binary.
ONE CANONICAL EXAMPLE To create a runnable "hello world" program, you create a file, for instance hello.go. The very first line must be package main. Somewhere in that file, you must define the entry point function: func main(). Inside this function, you can call other code, such as fmt.Println("Hello, world.") after importing the fmt package. Running go run hello.go will compile and execute this program.
Read the original → go.dev
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.