Fundamentals

Program Structure

Take a Go program apart to see how packages, imports, declarations, and the main entry point fit together.

What you will learn

This lesson takes a small program apart piece by piece so you can see what every part is for: the package clause, imports, declarations, and statements. You will also learn why Go starts at main, how several files can form one package, in what order things run at startup, and which compiler errors appear when a piece is missing.

The shape of a Go file

Every Go source file has the same three layers, always in this order: a package clause, then imports, then declarations. Here is a complete program:

main.go
package main

import "fmt"

const appName = "bootctl"

func main() {
    serverName := "CloudServer-1"

    for step := 1; step <= 3; step++ {
        fmt.Println(appName, "|", serverName, "is booting... step", step)
    }
}

Running it prints:

bootctl | CloudServer-1 is booting... step 1
bootctl | CloudServer-1 is booting... step 2
bootctl | CloudServer-1 is booting... step 3
PartIn the examplePurpose
Package clausepackage mainNames the package this file belongs to. It must be the first line of code.
Importsimport "fmt"Lists the other packages this file uses.
Declarationsconst appName, func mainIntroduce names: constants, variables, types, and functions.
StatementsserverName := ..., for ..., fmt.Println(...)Instructions that do work. They live inside function bodies.

The key distinction is between a declaration and a statement. A declaration introduces a name, so it can appear at the top level of a file. A statement performs an action, so it can only appear inside a function. If you try to write a statement at the top level, Go refuses:

package main

import "fmt"

fmt.Println("hello") // not allowed here
syntax error: non-declaration statement outside function body

Do not worry about understanding the for loop yet. It has its own lesson shortly.

Why execution starts at main

A library is a collection of code for other programs to use. An executable is a program that starts and runs. Go uses the package name to tell them apart:

  • package main means "build an executable".
  • Any other name, such as package greeting, means "build a library".

An executable also needs a starting point. By convention and by rule, that is a function named main that takes no arguments and returns nothing. If it is missing, the build fails:

function main is undeclared in the main package

When the program starts, Go does some setup work and then calls main. When main returns, the program exits, even if other work is still going on.

Imports

An import makes another package available in the current file:

import (
    "fmt"
    "os"
    "strings"
)

Use the parenthesised form once you have more than one import. A few rules matter:

  • You refer to a package by the last element of its path, so "strings" is used as strings.ToUpper(...).
  • Imports belong to a file, not a package. If two files in the same package both use fmt, each imports it.
  • An import you do not use is a compile error, as you saw in the first program lesson.
  • gofmt sorts imports alphabetically. By convention, standard library imports come first, then a blank line, then third-party and project imports.

Exported and unexported names

Go has no public or private keyword. Instead, the first letter of a name decides who can see it:

NameFirst letterVisible to
PrintlnUppercaseOther packages (exported)
printlnLowercaseOnly the same package (unexported)

This applies to functions, variables, constants, types, struct fields, and methods alike. It is one of the simplest rules in the language and one of the most important. Whenever you decide whether something is part of a package's public API, you do it by choosing a capital letter or not.

One package, many files

A package is a directory, and a directory can hold many .go files. They all start with the same package line, and Go compiles them together as one unit. Names declared at the top level of any file are visible in all the others, with no imports needed between them.

Create two files in the same folder:

main.go
package main

func main() {
    bootServer("api", 3)
}
server.go
package main

import "fmt"

func bootServer(name string, steps int) {
    for step := 1; step <= steps; step++ {
        fmt.Println(name, "booting... step", step)
    }
}

main.go calls bootServer without importing anything, because both files are in package main. Run the whole package:

Terminal
go run .

Now try running only one file:

Terminal
go run main.go
./main.go:4:2: undefined: bootServer

go run main.go compiles just that one file, so it cannot see server.go. This is why the lessons use go run ., which compiles the whole package.

The file names main.go and server.go are conventions. Go cares about the package line, not the file name.

What runs first

Before main runs, Go prepares the package. It first initialises package-level variables, then runs any init functions, and finally calls main:

package main

import "fmt"

var config = loadConfig()

func loadConfig() string {
    fmt.Println("1. package variable initialised")
    return "production"
}

func init() {
    fmt.Println("2. init runs")
}

func main() {
    fmt.Println("3. main runs, config =", config)
}
1. package variable initialised
2. init runs
3. main runs, config = production

An init function takes no arguments, cannot be called by you, and a package may even have several. Use it sparingly. Most setup is easier to follow when you call it explicitly from main.

Comments and line endings

A // comment runs to the end of the line, and /* ... */ spans several lines. A comment placed directly above a declaration, starting with the name, becomes its documentation:

// bootServer prints a boot message for each step.
func bootServer(name string, steps int) {

Go also inserts semicolons automatically at the end of certain lines, so you rarely write them. A side effect is that the opening brace must sit on the same line as its func, if, or for:

func main()
{
}
syntax error: unexpected semicolon or newline before {

The formatter prevents this mistake for you.

Common mistakes

  • Writing statements at the top level. Only declarations go outside functions.
  • Using go run main.go when the package has other files. Run go run . instead.
  • Forgetting that imports are per file. A file that uses strings must import it itself.
  • Using different package names in one directory. All files in a directory must declare the same package (test files aside).
  • Expecting lowercase names to be visible to other packages. They are not.

Practice

Add a function shutdownServer(name string) in a new file named shutdown.go. It should print a message such as api shutting down. Call it from main after booting. Then run go run main.go and explain the error.

Summary

A Go file contains a package clause, imports, and declarations, with statements living inside functions. The package named main builds an executable, and the function main is where it starts. A package can span many files, which share their top-level names, and imports belong to each file separately. A capital first letter exports a name, and startup runs package variables first, then init, then main.

Official reference: Packages in the Go language specification.

Ready to wrap up?

Mark this complete when you can explain the main idea and finish the practice task.

Copyright © 2026