Packages and main

How a Go program is organized, line by line

7 min read

Every Go program is made of packages. A package is a named bundle of code. Think of it like a labeled toolbox: the fmt package is a toolbox full of printing tools, and your own program lives in a toolbox too.

The first line of every file

Every Go file begins by saying which package it belongs to:

package main

The name main is special. It tells Go: this package is not a toolbox for other programs to borrow, it is a real, runnable program of its own. When you learn to build shared libraries later, they will use other package names, but every program you run starts with package main.

Borrowing tools with import

Go's standard library ships with dozens of ready-made packages. To use one, you import it by name:

import "fmt"

The name fmt is short for format, and it holds the printing tools we will use constantly. If you need more than one package, you list them inside parentheses, one per line:

import (
    "fmt"
    "strings"
)

Go keeps things tidy: if you import a package and never use it, the compiler refuses to build your program. It sounds strict, but it means real Go code never carries dead weight.

The main function

A function is a named block of steps. The function called main is where your program starts running:

func main() {

}

The word func starts a function, main is its name, the empty parentheses mean it takes no input, and the curly braces hold the steps. When the program runs, Go finds func main inside package main, runs its steps from top to bottom, and the program ends when the last step finishes.

Putting it all together

package main

import "fmt"

func main() {
    fmt.Println("Hello, Go!")
}

Here is the journey this file takes:

  1. package main declares this file is a runnable program.
  2. import "fmt" brings in the printing toolbox.
  3. func main() marks the starting point.
  4. fmt.Println(...) uses the Println tool from the fmt toolbox to print a line.

The dot in fmt.Println reads as from: use Println from fmt. You will see that dot pattern everywhere in Go.

Quick check

Q1 Why does a runnable Go program need package main?

Q2 Where does a Go program start running?

Want to save your progress? It's free.

Create a free account