Modules & Running Code
With Go installed, the next question is: how do you actually start a project? In most languages that means a config file with a name and a list of dependencies. Go's version of that is the module.
What a module is
A module is a directory tree of Go source files with a go.mod file at its
root. go.mod records the module's name (its import path) and the
minimum Go version it needs, and it's the unit Go uses for dependency
management — every package below it belongs to the same module unless a
subdirectory declares its own.
Create one with:
mkdir hello && cd hello
go mod init example/hello
That produces a go.mod file:
module example/hello
go 1.25
example/hello is just a name — it doesn't need to be a real URL unless
you plan to publish the module for others to go get.
A minimal program
Every Go program starts the same way: a package main declaration and a
func main() as the entry point.
// main.go
package main
import "fmt"
func main() {
fmt.Println("Hello, Go")
}
Save that as main.go next to your go.mod.
Three ways to run it
go run . # compile + run, nothing left on disk
go build # produce a binary named "hello" in the current directory
go install # build, then install the binary into your PATH
go run . is what you'll reach for while developing — it compiles to a
temporary location, runs it, and cleans up. go build is what you'd use to
produce a binary for distribution or deployment. go install does the same
build, but drops the result into $GOBIN (or $HOME/go/bin by default),
so if that's on your PATH, the command becomes available anywhere, like
any other CLI tool.
Package = directory
Every .go file belongs to a package, declared by that first line
(package main, package fmt, and so on). All files in one directory must
share the same package name. A main package is special: it's the one Go
looks for when you build a runnable command, and it must have a
func main(). Any other package name marks a library package — one that
other code imports rather than runs directly.
Adding a dependency
Real projects pull in code from elsewhere with go get:
go get github.com/some/library
This updates go.mod and downloads the package into your module cache.
The exercises on this site don't use this — the sandbox that runs your code
here has no network access, so every exercise sticks to the standard
library. On your own machine, go get is how you'd reach beyond it.
go get only ever adds. Delete the last import of a library and the
requirement stays in go.mod, claiming a dependency you no longer have.
The command that reconciles the file with reality is:
go mod tidy
It works in both directions: it adds anything your code imports but go.mod
is missing, and — the part nothing else does — it removes requirements
nothing imports any more. That pruning is why it's worth running before you
commit, so go.mod describes the code you actually wrote rather than every
library you once tried.