Install Go, write hello world, understand go run vs go build.
Packages, Imports, and Exported Names
Every Go file starts with a package declaration. A package is just a folder of
.go files that share a name. When you import that package, you get everything in
it that starts with a capital letter.
Packages
A directory of .go files = one package. By convention the folder name and the
package name match.
project/
├── main.go // package main
└── greet/
└── greet.go // package greet
Imports
Use the import keyword to bring in other packages — either standard library or
third-party modules.
If you import a package you don't use, the program won't compile. Go enforces tidiness — unused imports rot quickly and slow builds down, so the language refuses to ship them.
Grouping & aliases
By convention, imports are split into groups (stdlib first, third-party next),
separated by blank lines. goimports does this for you.
import (
"fmt"
"strings"
"github.com/google/uuid"
)
You can rename an import inline — useful when two packages share the same name:
import (
"encoding/json"
yamljson "github.com/ghodss/yaml" // local alias
)
The blank identifier _ lets you import a package purely for its side effects
(typically a func init() that registers a database driver, image format, etc.):
import _ "github.com/lib/pq" // registers the Postgres driver
Exported vs unexported names
Go has a one-rule visibility system:
- Names starting with a capital letter are exported — visible to other packages.
- Names starting with a lowercase letter are package-private.
package greet
func Hello(name string) string { // exported — anyone can call greet.Hello
return "hi, " + clean(name)
}
func clean(s string) string { // unexported — only files in `greet` can call it
return strings.TrimSpace(s)
}
This even applies to struct fields. In type User struct { Name string; age int },
other packages can read u.Name but cannot see u.age.
The standard library
Go ships with a famously thorough standard library. A few you'll use immediately:
| Package | What it does |
| --------------- | ------------------------------------------- |
| fmt | Formatted I/O (Println, Printf, Sprintf). |
| strings | Manipulate UTF-8 strings. |
| strconv | Convert strings ↔ numbers. |
| os | OS calls, env vars, os.Args. |
| io | Reader / Writer interfaces. |
| net/http | HTTP client and server. |
| encoding/json | JSON encode / decode. |
| time | Times, durations, tickers. |