28 packages · 9 parts · the stdlib you'll actually import
Go Standard Library 101
The companion volume to Learn Go 101, the standard library packages you'll actually reach for, grouped by what you're trying to do instead of alphabetically. No "here's what a package is" filler, just the functions you'll use and the ones that'll bite you.
curriculum
part_01 · strings_and_formatting
01 fmt: Formatting Verbs
You've been using fmt.Println since line one of Learn Go 101. What you probably haven't used yet is the full verb set Printf-family functions understand, this is Go's answer to template literals plus console.log's object inspection, in one mini-language:
| Verb | Prints | Example output |
|---|---|---|
%v | default format, any type | {1 2} |
%+v | default, struct fields named | {X:1 Y:2} |
%#v | Go-syntax representation | main.Point{X:1, Y:2} |
%T | the type itself | main.Point |
%d / %.2f | integer / fixed-precision float | 42 / 3.14 |
%s / %q | string / quoted-and-escaped string | hi / "hi" |
%x | hex | ff |
%t | bool | true |
type Point struct{ X, Y int }
p := Point{1, 2}
fmt.Printf("%v\n", p) // {1 2}
fmt.Printf("%+v\n", p) // {X:1 Y:2}
fmt.Printf("%#v\n", p) // main.Point{X:1, Y:2}
fmt.Printf("%T\n", p) // main.Point
fmt.Printf("%5d|%-5d|\n", 42, 42) // " 42|42 |", width, and left-align with -
fmt.Printf("%.2f\n", 3.14159) // 3.14
Three functions cover almost every real use case: Sprintf builds a string, Fprintf writes to any io.Writer, and Errorf builds an error (with %w for wrapping, as in Errors As Values):
msg := fmt.Sprintf("user %d: %s", 42, "ada") // build a string
fmt.Fprintf(os.Stderr, "warning: %s\n", "low disk") // write to any io.Writer
err := fmt.Errorf("loading config: %w", innerErr) // build a wrapped error
%v is doing the job of both template-literal interpolation and console.log's "pretty print any object" behavior at once. The difference is it's driven by an explicit format string instead of magic runtime inspection, closer to C's printf than to console.log.
part_01 · strings_and_formatting
02 strings: The Toolkit
This is the package you'll import in almost every file. Most of it maps directly onto String.prototype methods you already reach for daily:
s := " Hello, Go! "
strings.TrimSpace(s) // "Hello, Go!"
strings.Contains(s, "Go") // true
strings.ToUpper(s) // " HELLO, GO! "
strings.Split("a,b,c", ",") // []string{"a", "b", "c"}
strings.Join([]string{"a", "b", "c"}, "-") // "a-b-c"
strings.Fields(" foo bar baz ") // []string{"foo","bar","baz"}, splits on any run of whitespace
strings.Replace("aaa", "a", "b", 2) // "bba", replace first 2 occurrences
strings.ReplaceAll("aaa", "a", "b") // "bbb"
strings.HasPrefix("main.go", "main") // true
The one function here with no obvious JS analog, and the one worth actually remembering, is strings.Builder, for whenever you're assembling a string in a loop:
var b strings.Builder
for i := 0; i < 1000; i++ {
b.WriteString("x")
}
result := b.String() // O(n) total work
Go strings are immutable, so result += "x" inside a loop allocates a brand-new string every single iteration, O(n²) total work as the string grows. JS engines quietly optimize this pattern for you; Go's compiler doesn't. strings.Builder writes into a growing buffer instead and is the idiomatic fix.
part_01 · strings_and_formatting
03 strconv: Conversions
Beyond the Atoi/Itoa shortcut pair, strconv's Parse* functions take a base and bit size, which matters the moment you're parsing anything besides plain base-10 int:
n, err := strconv.Atoi("42") // convenience wrapper for base-10 int
i64, err := strconv.ParseInt("ff", 16, 64) // hex string → int64
f, err := strconv.ParseFloat("3.14", 64)
b, err := strconv.ParseBool("true") // also accepts "1", "t", "T", "TRUE"...
s := strconv.FormatInt(255, 16) // "ff", the reverse direction
q := strconv.Quote("hi\tthere") // `"hi\tthere"`, Go-syntax quoted string
Every Parse* function returns an error as its second value, the same as parseInt silently returning NaN in JS, except Go forces you to look at it. Discarding it with n, _ := strconv.Atoi(userInput) on untrusted input is how "NaN propagating three functions downstream" bugs become "silent zero propagating three functions downstream" bugs instead, just as hard to trace.
part_02 · collections
04 slices: Generic Helpers
Added in Go 1.21, the slices package is what Array.prototype looks like once it's generic and standalone rather than built into the type. If you've been reaching for sort.Slice boilerplate or hand-rolled contains helpers, this replaces most of that:
nums := []int{5, 2, 8, 1}
slices.Sort(nums) // in-place, [1 2 5 8]
slices.Contains(nums, 8) // true
slices.Index(nums, 8) // 3
slices.Reverse(nums) // in-place, [8 5 2 1]
slices.Max(nums) // 8
slices.Equal(nums, []int{8, 5, 2, 1}) // true, slices themselves can't use == directly
For custom ordering, slices.SortFunc takes a comparison function returning negative/zero/positive, the same contract as Array.prototype.sort's comparator, minus the historical "returns a boolean" footgun some older JS code still has:
type Person struct {
Name string
Age int
}
people := []Person{{"Bob", 30}, {"Ada", 25}}
slices.SortFunc(people, func(a, b Person) int {
return a.Age - b.Age // negative: a < b, zero: equal, positive: a > b
})
part_02 · collections
05 maps: Generic Helpers
The maps package's sibling functions cover the operations Go's built-in map type doesn't hand you directly. As of Go 1.23, Keys and Values return iterators (iter.Seq) rather than slices, you can range over them directly, or materialize a slice with slices.Collect when you actually need one:
m := map[string]int{"a": 1, "b": 2, "c": 3}
for k := range maps.Keys(m) { // iterator, no intermediate slice allocated
fmt.Println(k)
}
keys := slices.Collect(maps.Keys(m)) // []string, only when you actually need a slice
maps.DeleteFunc(m, func(k string, v int) bool {
return v < 2 // drops "a"
})
clone := maps.Clone(m) // shallow copy, a new map, same value types
maps.Equal(m, clone) // true
Iteration order is still randomized underneath, same as a plain range over a map (Maps, in the language guide), maps.Keys doesn't change that, it just gives you a composable iterator instead of writing the collection loop by hand every time.
part_02 · collections
06 sort: Custom Ordering
Before generics, this was the only way to sort anything custom, and you'll still see it constantly, since it predates slices.SortFunc and most existing Go code was written before 1.21:
nums := []int{5, 2, 8, 1}
sort.Ints(nums) // shortcut for the built-in numeric slice types, [1 2 5 8]
people := []Person{{"Bob", 30}, {"Ada", 25}}
sort.Slice(people, func(i, j int) bool {
return people[i].Age < people[j].Age // compares by index, no bounds safety net
})
For new code, prefer slices.SortFunc, it compares elements directly instead of juggling indices, so there's a whole class of off-by-one bugs it makes impossible to write. Reach for sort.Slice only when you're touching pre-1.21 code, or need sort.Stable, which slices doesn't provide a direct equivalent for.
part_02 · collections
07 bytes: Byte Slices
bytes mirrors strings' API almost function-for-function, but operates on []byte instead of string, reach for it when you're avoiding the allocation cost of converting back and forth in a hot path. bytes.Buffer is the []byte counterpart to strings.Builder, and additionally implements both io.Reader and io.Writer:
var buf bytes.Buffer
buf.WriteString("hello ")
buf.WriteString("world")
fmt.Println(buf.String()) // "hello world"
bytes.Contains([]byte("hello"), []byte("ell")) // true
bytes.Equal([]byte("a"), []byte("a")) // true, byte slices can't use == directly, same reason slices can't
part_03 · time_and_math
08 time: Dates & Durations
time.Duration is a real type, not milliseconds-as-a-number, which means duration math reads like English instead of requiring you to remember which unit you multiplied by:
now := time.Now()
later := now.Add(2 * time.Hour)
diff := later.Sub(now) // a Duration
fmt.Println(diff) // 2h0m0s
time.Sleep(500 * time.Millisecond) // reads naturally, no "500" floating unitless
start := time.Now()
doWork()
fmt.Println("took", time.Since(start)) // shorthand for time.Now().Sub(start)
Formatting and parsing dates is the part that catches everyone once, and only once, Go doesn't use strftime-style %Y-%m-%d codes or token letters like YYYY-MM-DD. Instead, you write a layout string using the literal digits of one specific reference moment:
t := time.Now()
fmt.Println(t.Format("2006-01-02 15:04:05")) // e.g. 2026-07-21 14:30:00
// The reference moment, memorize it once:
// Mon Jan 2 15:04:05 MST 2006 → 01/02 03:04:05PM '06 -0700
// Every layout string is spelled using THESE exact digits, in whatever order/format you want
The reference date is January 2, 2006, 3:04:05 PM, deliberately chosen because its components read 01/02 03:04:05PM '06, ascending. Want YYYY-MM-DD? Write "2006-01-02". Want a 12-hour clock? Write "3:04 PM". There's no way to guess this from first principles, every Go developer just looks it up (or bookmarks this page) the first dozen times.
part_03 · time_and_math
09 math & math/rand
The usual numeric toolbox, plus one wrinkle: math.Max/math.Min only work on float64, because they predate generics. Go 1.21 added true generic max()/min() as builtins, no import required, and they work on ints too:
math.Sqrt(16) // 4
math.Pow(2, 10) // 1024
math.Round(3.5) // 4
math.Max(3.0, 7.0) // 7, float64 only, and requires the import
max(3, 7) // 7, the builtin (Go 1.21+): no import, works on any ordered type
Randomness got a real upgrade in math/rand/v2 (Go 1.22+): it's automatically seeded, so the old rand.Seed(time.Now().UnixNano()) boilerplate at the top of every main() is finally unnecessary:
import "math/rand/v2"
n := rand.IntN(100) // [0, 100), auto-seeded, no setup needed
f := rand.Float64() // [0.0, 1.0)
math/rand (and v2) is not cryptographically secure, predictable enough that it's unsafe for tokens, session IDs, or anything else where an attacker guessing the next value matters. For that, skip ahead to crypto/rand in Part IX.
part_04 · io
10 io: Readers & Writers
Learn Go 101 introduced io.Reader/io.Writer as the canonical small-interface example. The payoff is the handful of functions built entirely on top of them, they work with a file, a network connection, an HTTP body, or an in-memory buffer, completely interchangeably:
n, err := io.Copy(dst, src) // streams src into dst until EOF, any Reader, any Writer
data, err := io.ReadAll(resp.Body) // read an entire Reader into memory in one call
io.MultiWriter composes several writers into one, a single write fans out to all of them, which is exactly how you'd log to a terminal and a file simultaneously without duplicating every call site:
mw := io.MultiWriter(os.Stdout, logFile)
fmt.Fprintln(mw, "logged and printed, in one call")
And io.EOF, a plain sentinel error value, nothing more, is how a Reader tells you "there's genuinely nothing left," which is expected control flow, not a failure to handle specially:
buf := make([]byte, 4)
n, err := reader.Read(buf)
if err == io.EOF {
// no more data, expected, not exceptional
}
part_04 · io
11 bufio: Buffered I/O
Beyond the line-scanning from Files & the OS, bufio.Scanner takes a split function that controls what counts as one "token", swap it out and the exact same scan loop switches from lines to words:
scanner := bufio.NewScanner(os.Stdin)
scanner.Split(bufio.ScanWords) // default is bufio.ScanLines, this switches it
for scanner.Scan() {
fmt.Println(scanner.Text())
}
bufio.Writer batches small writes into fewer, larger syscalls, genuinely faster for lots of small writes, but that buffering means nothing is guaranteed to actually land until you flush it:
w := bufio.NewWriter(file)
w.WriteString("buffered output\n")
w.Flush() // nothing is guaranteed written until this runs
A forgotten Flush() is the classic bufio.Writer bug: the program exits, the buffer never empties, and your output silently vanishes with no error anywhere. defer w.Flush() right after creating the writer is the idiomatic guard, the same reflex as defer f.Close().
part_04 · io
12 path/filepath
Never hand-build a file path with string concatenation, filepath.Join uses the correct separator for the OS you're compiling for, which matters the instant your code touches Windows:
p := filepath.Join("data", "2026", "report.csv") // OS-correct separators, always
filepath.Base(p) // "report.csv"
filepath.Dir(p) // "data/2026"
filepath.Ext(p) // ".csv"
filepath.WalkDir (the modern, faster replacement for the older Walk) recursively visits every file under a root:
filepath.WalkDir(".", func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
fmt.Println(path)
return nil
})
This is Node's path.join, and the same warning applies: string-concatenating paths with "/" works fine in dev on macOS/Linux and breaks in production the day someone runs it on Windows. filepath.Join costs nothing and removes the whole bug class.
part_05 · pattern_matching_and_templates
13 regexp: Pattern Matching
Go's regex flavor (RE2) trades a little expressive power, no backreferences, no lookahead, for a hard guarantee: no catastrophic backtracking, ever. Every match runs in linear time, which matters the moment you're matching against untrusted input:
re := regexp.MustCompile(`\d+`) // MustCompile panics on an invalid pattern
re.MatchString("room 42") // true
re.FindString("room 42") // "42"
re.FindAllString("a1 b22 c333", -1) // []string{"1", "22", "333"}, -1 means "no limit"
re.ReplaceAllString("room 42", "X") // "room X"
Named groups make extraction self-documenting instead of counting capture-group indices by hand:
re := regexp.MustCompile(`(?P<year>\d{4})-(?P<month>\d{2})`)
match := re.FindStringSubmatch("2026-07")
for i, name := range re.SubexpNames() {
if name != "" {
fmt.Println(name, "=", match[i])
}
}
// year = 2026
// month = 07
MustCompile is only safe for patterns that are compile-time literals, it panics immediately if the pattern is malformed, which is fine for catching a typo at startup. Never call it on a pattern built from user input; use regexp.Compile there and actually check the returned error.
part_05 · pattern_matching_and_templates
14 unicode/utf8: Runes
Basic Types & Conversion in the language guide showed that len() counts bytes, not characters. utf8.RuneCountInString is the function that actually answers "how many characters," and unicode gives you rune-level classification for anything Go's ASCII-only string helpers don't cover:
s := "héllo"
len(s) // 6, bytes
utf8.RuneCountInString(s) // 5, actual character count
unicode.IsLetter('é') // true
unicode.IsDigit('5') // true
unicode.ToUpper('é') // 'É', rune-level; strings.ToUpper does the whole string at once
JS strings are UTF-16, so "👍".length is 2 for a reason most JS developers have never had to think about. Go strings are UTF-8 bytes, so len("👍") is 4, different encoding, same underlying lesson: never assume .length/len() equals "number of characters" in any language, ever.
part_05 · pattern_matching_and_templates
15 text/template & html/template
Go's templating uses {{.Field}} placeholders, {{range}} loops, and {{if}} conditionals against whatever data you hand Execute:
tmpl := template.Must(template.New("greeting").Parse(
"Hello, {{.Name}}! You have {{len .Items}} items.\n"))
tmpl.Execute(os.Stdout, struct {
Name string
Items []string
}{Name: "Ada", Items: []string{"a", "b"}})
// Hello, Ada! You have 2 items.
html/template is a drop-in replacement with the identical API, the entire difference is that it understands it's generating HTML, and escapes every interpolated value for the specific context it lands in (element text, an attribute, a <script> block, each escaped differently, correctly):
t1 := template.Must(template.New("t").Parse("Comment: {{.C}}"))
t1.Execute(os.Stdout, data) // text/template: renders data.C exactly as given, always
t2 := htmltemplate.Must(htmltemplate.New("t").Parse("Comment: {{.C}}"))
t2.Execute(os.Stdout, data) // html/template: markup inside data.C is escaped into inert text
If data.C came from a user and contained <script>alert(1)</script>, text/template would print it out as live markup, a textbook stored XSS. html/template renders the same value as harmless text automatically. The rule of thumb: any time you're generating HTML, use html/template, never text/template, there's no scenario where the plain version is the safer choice.
part_06 · encoding
16 encoding/json, Deeper
Learn Go 101 covered Marshal/Unmarshal. For large payloads or long-lived connections, NewEncoder/NewDecoder stream directly against an io.Writer/io.Reader instead of materializing an intermediate []byte:
enc := json.NewEncoder(os.Stdout)
enc.Encode(user) // writes straight out, ideal for JSON Lines or very large payloads
dec := json.NewDecoder(resp.Body)
dec.Decode(&user) // reads straight in, no intermediate byte slice
A type implementing MarshalJSON controls its own encoding entirely, handy for turning an internal representation like an iota-based enum into something readable on the wire:
type Status int
const (
Active Status = iota
Inactive
)
func (s Status) MarshalJSON() ([]byte, error) {
names := map[Status]string{Active: "active", Inactive: "inactive"}
return json.Marshal(names[s]) // serialize as a readable string instead of a bare int
}
And json.RawMessage lets you defer decoding part of a payload, useful for envelope formats where the shape of payload depends on type:
type Event struct {
Type string `json:"type"`
Payload json.RawMessage `json:"payload"` // kept as raw bytes, decode later, once Type is known
}
part_06 · encoding
17 base64 & hex
Two functions cover almost every binary-to-text need, and the one decision that actually matters is which base64 alphabet you pick:
encoded := base64.StdEncoding.EncodeToString([]byte("hello")) // "aGVsbG8="
decoded, err := base64.StdEncoding.DecodeString(encoded) // []byte("hello")
// StdEncoding uses + and /, unsafe to drop straight into a URL or filename
urlSafe := base64.URLEncoding.EncodeToString([]byte("hello?")) // uses - and _ instead
hex.EncodeToString([]byte{0xDE, 0xAD, 0xBE, 0xEF}) // "deadbeef"
Using StdEncoding for something that ends up in a URL query param or a filename is a recurring bug, the + and / characters need percent-encoding on top, or just break outright. Reach for URLEncoding the moment the output's destination is a URL.
part_06 · encoding
18 encoding/csv
Handles quoting and escaping correctly, which is the entire reason not to split on commas by hand:
r := csv.NewReader(file)
records, err := r.ReadAll() // [][]string, every row, every field, quoting handled for you
w := csv.NewWriter(file)
w.Write([]string{"name", "age"})
w.Write([]string{"Ada", "30"})
w.Flush() // same rule as bufio.Writer, nothing's written until you flush
part_07 · networking
19 net/http: Full Toolkit
HTTP Servers & Clients covered the basics. The single most important thing missing from that intro: http.DefaultClient, and therefore plain http.Get, has no timeout at all. A hung upstream server blocks forever, quietly, until your own service runs out of goroutines or connections:
client := &http.Client{
Timeout: 10 * time.Second, // always set this explicitly, the zero value means "never"
}
resp, err := client.Get("https://api.example.com/data")
This is a genuinely common production incident, not a theoretical one: one slow dependency, no client timeout, and every goroutine in your service eventually piles up waiting on a response that's never coming. Constructing your own http.Client with a Timeout should be the default, not an afterthought.
On the server side, http.Error sets the status code and writes a plain-text body in one call, the piece the earlier intro skipped by only ever returning 200s:
mux.HandleFunc("GET /users/{id}", func(w http.ResponseWriter, r *http.Request) {
user, err := findUser(r.PathValue("id"))
if err != nil {
http.Error(w, "user not found", http.StatusNotFound) // status + body, one call
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(user)
})
part_07 · networking
20 net/url: URLs & Query Strings
url.Parse breaks a URL into its components, already decoded, reaching for regex or manual string splitting here is a common, entirely unnecessary habit to drop:
u, err := url.Parse("https://example.com/search?q=go+lang&page=2")
u.Query().Get("q") // "go lang", already decoded
u.Path // "/search"
u.Host // "example.com"
Building a URL is the direction that actually bites people: hand-concatenating query parameters breaks the moment a value contains a character that needs encoding. url.Values handles it correctly:
v := url.Values{}
v.Set("q", "go & typescript") // string concatenation would mangle this
v.Set("page", "2")
u2 := &url.URL{Scheme: "https", Host: "example.com", Path: "/search", RawQuery: v.Encode()}
fmt.Println(u2.String())
// https://example.com/search?page=2&q=go+%26+typescript
part_07 · networking
21 net: TCP Fundamentals
Worth a quick look at what net/http is actually built on, since the pattern underneath it is the same "one goroutine per connection" idea from Goroutines in the language guide, applied directly:
ln, err := net.Listen("tcp", ":9000")
defer ln.Close()
for {
conn, err := ln.Accept() // blocks until a client connects
if err != nil {
continue
}
go handleConn(conn) // exactly how net/http scales to many concurrent connections
conn, err := net.Dial("tcp", "example.com:80")
defer conn.Close()
conn.Write([]byte("GET / HTTP/1.1\r\nHost: example.com\r\n\r\n"))
part_08 · concurrency_and_system
22 sync/atomic
For a single counter or flag shared across goroutines, a full sync.Mutex (sync: Mutexes & WaitGroups) is often more than you need. Since Go 1.19, atomic gives you real typed wrappers instead of the old pattern of passing a bare *int64 to package-level functions and hoping every call site remembers to use them:
var counter atomic.Int64 // a real type, impossible to accidentally touch non-atomically
counter.Add(1)
counter.Load() // read safely from any goroutine
counter.CompareAndSwap(5, 10) // swap only if the current value is still 5
Rule of thumb: atomic for one independent value (a counter, a boolean flag), sync.Mutex for a group of related fields that need to change together as one unit. Reaching for atomics on multiple fields you also need to stay consistent with each other is a common source of subtle races.
part_08 · concurrency_and_system
23 os/exec: Subprocesses
Running another program and capturing its output, Node's child_process, essentially:
cmd := exec.Command("git", "rev-parse", "HEAD")
output, err := cmd.CombinedOutput() // stdout + stderr together, as []byte
cmd2 := exec.Command("ls", "-la")
cmd2.Dir = "/tmp" // run in a specific directory
cmd2.Env = append(os.Environ(), "FOO=bar") // inherit the environment, plus one more
err = cmd2.Run() // just run it, no output capture
exec.Command never invokes a shell, exec.Command("ls -la") as one string fails outright; each argument is its own string, as shown above. This is also exactly why os/exec is safe from shell injection as long as you keep it that way: pass user input as separate argument strings, never build a command by concatenating it into a shell string and handing that to sh -c.
part_08 · concurrency_and_system
24 os/signal: Graceful Shutdown
signal.NotifyContext turns OS signals into something that composes directly with everything from Context & Concurrency Patterns, no channel plumbing required. This is the complete, idiomatic shutdown pattern for a server:
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
srv := &http.Server{Addr: ":8080"}
go srv.ListenAndServe()
<-ctx.Done() // blocks here until SIGINT or SIGTERM arrives
fmt.Println("shutting down…")
shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
srv.Shutdown(shutdownCtx) // finishes in-flight requests, then stops, no dropped connections
part_08 · concurrency_and_system
25 flag: Command-Line Flags
No dependency needed for basic CLI argument parsing, the standard library covers the common case directly:
port := flag.Int("port", 8080, "port to listen on")
verbose := flag.Bool("v", false, "enable verbose logging")
flag.Parse()
fmt.Println(*port, *verbose) // flag functions return pointers, dereference to read the value
fmt.Println(flag.Args()) // anything left over after flags, positional arguments
9000 true
[extra-arg]
For anything beyond a handful of flags, subcommands, shorthand aliases, auto-generated help text, most teams reach for a third-party package (cobra is the most common). Same story as net/http versus a full router: the standard library is a solid floor, not a ceiling.