The module and the first program

What a module is, why go.mod exists, and why you run a program as a package rather than as a single file.

Go has no "framework project". The unit of code you compile and hand to other people is a module: a directory with a go.mod file. That file records the module path and the language version.

go mod init example.com/hello

The module path is the name by which this code will be imported. Any name is fine for a learning directory. For a service, people usually take the repository path, even if the module is not published anywhere yet: imports inside it are built from that path.

A minimal program looks like this:

package main

import "fmt"

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

package main together with the function main is the entry point of the program. Any other package is a library: you do not "run" it, you import it. A directory contains exactly one package. The package name usually matches the directory name. The exception is main.

Run the whole package:

go run .

The dot means "the package in the current directory". The command go run main.go compiles only the files you listed. While there is a single file, there is no difference. As soon as config.go and main.go appear, running one file breaks: the compiler does not see the rest of the package's declarations.

Next to go.mod, after the first build that pulls dependencies, go.sum appears. Commit it: it holds checksums of the modules you have already downloaded. The module directory itself does not have to live in GOPATH. With modules, and they have been required for many years, code can live anywhere.

What to keep in mind

The command go env GOPATH still shows a service directory for the cache and for old projects, but new services do not depend on it. The version in go.mod (go 1.22, go 1.26) is not "the version that happened to be installed on the laptop". It is a contract: which language rules the module uses. Set the version whose behavior you actually understand.

The tools gofmt and go test work from the module. From the repository root, go test ./... walks every package. The habit of running checks from a random subdirectory that has no module is a common source of "it builds for me, and CI disagrees".

Practice

  1. What a module is

    What is a module in modern Go?

    • Any file with the .go extension
    • A directory with go.mod, the boundary of dependencies and imports
    • Only a directory inside GOPATH/src
    • Necessarily a git repository with a version tag
  2. How to run it

    The directory holds main.go and config.go, both in package main. Which invocation builds the whole program?

    • go run main.go
    • go run .
    • go run -work
    • go file main.go config.go
  3. The first program

    Finish the program so that it prints exactly Hello, Tropa and then exits. The package is main, and printing goes through fmt.