liveBook · Manning

Main package

As explained in Go in Action, Second Edition

The main package is the special Go package whose compiled program is intended to be an independently runnable executable.

The main package is Go’s special executable package. When a directory contains package main, the compiler searches its files for a main function and produces one independently runnable executable. section 2.4.5

Other packages can be named for their purpose and imported as libraries. The main package identifies where an application starts, while package boundaries organize concerns and control visibility. section 2.4.5 section 11.1.1

Use main package deliberately when structuring executable projects:

  • Keep each executable’s main package and main function in its own subdirectory, commonly under cmd, such as cmd/myapp/main.go. section 11.1.1
  • Share reusable logic through purpose-specific packages rather than placing every concern in main; Go rejects circular package dependencies. section 11.1.1
  • Use internal for implementation code that external applications must not import; the compiler enforces its directory-tree visibility boundary. section 11.1.1

Minimal executable declaration

A file beginning with package main declares participation in an executable package. Add a main function to provide the program’s starting point; the compiler then emits a single runnable executable. section 2.4.5

Listing 2.8 Declaring package main
package main

View the minimal package declaration that marks a Go file as belonging to the executable package. section 2.4.5

How Go in Action, Second Edition covers it

How deep it goes
Explains compiler discovery of main and main(), then extends into executable directory organization and package constraints.
Examples
Uses a package declaration listing, cmd/myapp/main.go, and a multi-module go-news directory structure.
What you can do after
Build an independently runnable executable by combining package main with a main function.
How it connects
Connects packages, the main function, executables, imports, internal packages, and directory organization.

Also explained in

Compare how 2 books explain main package →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Go in Action, Second Edition. The section links point to the parts of the book it draws on.