Go Primer — From Zero to Working Code
"The language the cloud is built from — Docker, Kubernetes, Terraform, Prometheus — taught from your very first line, with every incantation explained."
01 · The hookThe Interview Where They Hand You Someone Else's Code
"Half of my interview is one exercise. I open the source of a tool the candidate claims to use every day — some weeks it's a slice of Caddy's server code, some weeks the request loop of our own API gateway — and I ask them to read it with me. Not write it. Read it. The room splits instantly. For one kind of candidate, everything below the YAML is a sealed black box: Docker is a command, Kubernetes is a mystery, and a page of Go might as well be Sanskrit. The other kind has written maybe five hundred lines of Go — a little link checker, a toy server — and suddenly they're pointing at the screen: that's a goroutine per request, that channel is the queue, and if nobody closes it, isn't that a leak? It was a leak. It was, in fact, the exact leak from our incident three weeks earlier. We hired her."
Here's the open secret of the cloud era: the infrastructure layer speaks one language. Docker, Kubernetes, Terraform, Prometheus — the tools that run everyone else's code — are Go programs. So is much of the plumbing around the services in this track: Prometheus and Grafana, which watch your services (E7), are Go; Caddy and Traefik, the reverse proxies in front of them, are Go; CockroachDB is Go; and when a team needs a gateway, a CLI, or a Kubernetes operator that starts in milliseconds and ships as one file, they reach for Go. Engineers who can read and write this layer cluster in platform and infrastructure roles — the roles that every backend estate needs filled, because every service ultimately stands on infrastructure someone has to run.
This chapter teaches Go from zero — no prior programming required, only general computer literacy — in roughly ten honest hours. Go is famously the quickest mainstream language to learn: the entire specification is smaller than Java's chapter on generics, and that's a deliberate design position, not an accident. By the end you'll have built a concurrent link checker (the classic first Go project), and you'll be the candidate reading the gateway source out loud.
Two everyday ideas carry this whole chapter. First: a Go program compiles to a
single finished file, the way a video exports to one .mp4 —
you can play it on any device without owning the editing software. Most languages instead
hand the target machine a recipe plus a requirement to own the kitchen (an
interpreter or virtual machine); Go hands it the finished cake. Second:
concurrency, Go's signature feature, is a busy restaurant kitchen. Cooks
(goroutines) work independently; they never shout across the room or grab from each
other's stations — they pass plates through the serving hatch (channels). Many hands, one
orderly flow of plates. That picture, made precise, is section 09.
02 · Getting set upOne Install, One File, Every Word Explained
Install Go from go.dev/dl — one installer, no choices to
agonize over. As of August 2026 the current stable line is
Go 1.26 (1.26.6 shipped August 13, 2026), with Go 1.27 due before the month
is out; everything in this chapter runs identically on either, and was verified against
1.26.6. Check your install with go version. That one go command is
the entire toolchain — compiler, dependency manager, test runner, formatter — which is your
first taste of Go's personality: one obvious way, batteries included,
nothing to configure.
// Run with: go run hello.go
package main
import "fmt"
func main() {
fmt.Println("Hello, Go")
}
Every word, once, properly. package main — every Go file begins by naming
the package it belongs to; packages are how Go groups code, and the name main
is special: it means "this builds into a runnable program, not a library".
import "fmt" — pull in the format package from the standard library,
home of printing and formatting. Imports are per-file, and here's an early dose of Go
opinion: an import you don't use is a compile error, not a warning (section 04
explains why). func main() — the entry point, the function the program starts
with. Notice what's absent: no class wrapping it, no public static void
ceremony — Go functions live at the top level of a file. And
fmt.Println(...) — call Println from the fmt package.
That capital P is not a style choice: in Go, a capitalized name is public
(usable from other packages) and a lowercase name is private to its package. Visibility is
spelled into the name itself — no keywords required.
go run hello.go compiles and executes in one step — your inner loop while
learning. The command that explains Go's grip on the infrastructure world, though, is
go build:
go build produces one self-contained executable: nothing to install on the target machine. Interpreter and VM languages ship source-plus-runtime instead; Go ships the finished file.Run go build hello.go and you get a file named hello — on the
author's test machine, a 2.4 MB statically linked executable. Copy it to a
server that has never heard of Go and it runs. No interpreter to install, no dependency
folder to ship, no version mismatch on the target. This is why ops teams love Go and why the
tools they build (Docker, Kubernetes, Terraform) are written in it — a claim we'll cash out
properly, with cross-compilation, in section 10.
03 · Core GoValues & Types — Zero Values and the End of "Undefined"
Go is statically typed — every variable has one fixed type, and
programs that violate a type refuse to compile — but it wears typing lightly:
count := 42 declares and initializes, inferring the type from the
right-hand side. The long form, var count int, matters for a subtler reason.
Most languages leave an unassigned variable undefined or null, a landmine
that explodes at runtime. Go instead gives every type a zero value — a
useful default that makes a declared variable immediately safe to use: 0 for
numbers, false for booleans, "" for strings. "No undefined,
ever" is a small philosophical decision with enormous consequences — you'll see it again in
maps (section 08).
| Type | Holds | Example | Zero value / notes |
|---|---|---|---|
int | Whole numbers | count := 42 | 0 · machine-sized (64-bit); sized variants like int32, int64 exist when width matters |
float64 | Decimals | price := 199.99 | 0.0 · the default for decimal literals |
bool | true / false | paid := true | false · no truthiness — only booleans branch |
string | Immutable UTF-8 text | name := "Asha" | "" · len() counts bytes; []rune counts characters |
// Run with: go run values.go
package main
import "fmt"
func main() {
// := declares AND initializes in one stroke -- the type is inferred
// from the right-hand side. count is an int forever after this line.
count := 42
price := 199.99
paid := true
name := "Asha"
// var is the long form -- needed when you declare WITHOUT a value.
// And here is Go's big idea: no undefined, no null surprises. Every
// type has a ZERO VALUE -- 0, 0.0, false, "" -- a useful default, always.
var retries int
var label string
var ok bool
fmt.Println(retries, ok, label == "") // 0 false true
// Constants are fixed at compile time; reassigning one won't compile.
const maxAttempts = 3
// fmt.Printf formats with verbs: %d int, %f float, %s string,
// %t bool, %q quoted string, %v anything, %T "what type is this?"
fmt.Printf("%d %s paid=%t\n", count, name, paid) // 42 Asha paid=true
fmt.Printf("%.2f\n", price) // 199.99
fmt.Printf("%v is a %T\n", maxAttempts, maxAttempts) // 3 is a int
// Strings are immutable bytes. A RUNE is one Unicode character --
// and len() counts BYTES, which matters the moment text isn't English:
word := "नमस्ते"
fmt.Println(len(word)) // 18 -- bytes!
fmt.Println(len([]rune(word))) // 6 -- characters
// Static typing, minus the ceremony. This line would NOT compile:
// count = "hello" // cannot use "hello" (untyped string) as int value
fmt.Println(count + 1) // 43
}
Two habits to install now. First, read %v and %T as your
debugging flashlights — "print anything" and "tell me its type". Second, respect the
byte/rune split: Go strings are raw UTF-8 bytes, so len("नमस्ते") is 18, not 6.
English text hides this; real-world text — names, addresses, anything your users type —
does not.
Predict all four lines before running. Hint: zero values, and the fact
that 10 and 10.0 are different types.
package main
import "fmt"
func main() {
var a int
var s string
b := a + 1
fmt.Println(a, b)
fmt.Println(s == "", len(s))
fmt.Println(10 / 4)
fmt.Println(10.0 / 4)
}
Reveal the answer
0 1 — the zero value is a real, usable 0. true 0 — the zero
string is empty, length 0, no null in sight. 2 — both operands are
integers, so Go does integer division and truncates. 2.5 — one
float operand rescues the math. The integer-division trap is universal across languages;
Go's twist is that it will at least never let you divide an int by a string.
04 · Core GoControl Flow — One Loop, Opinionated on Purpose
Go's control flow kit fits in one breath: if, switch, and
exactly one looping keyword — for — which wears three shapes. No
parentheses around conditions (the formatter would strip them anyway), braces always
mandatory, and two genuine improvements over the C family: an if can open with
its own tiny init statement, and switch does not fall
through from case to case — Go fixed C's oldest bug by default.
// Run with: go run control.go
package main
import "fmt"
func main() {
marks := 78
// if: no parentheses (gofmt would delete them), braces mandatory.
if marks >= 60 {
fmt.Println("first class")
}
// The if INIT statement: declare something that lives only inside
// this if/else -- tidy scoping you'll use constantly with errors.
if half := marks / 2; half > 30 {
fmt.Println("half is", half)
}
// fmt.Println(half) // would not compile -- half is gone
// switch: NO fallthrough by default. Each case breaks itself;
// several values share a case with commas.
day := "SAT"
switch day {
case "SAT", "SUN":
fmt.Println("weekend")
default:
fmt.Println("weekday")
}
// A switch with no subject at all: a cleaner else-if chain.
switch {
case marks >= 90:
fmt.Println("distinction")
case marks >= 60:
fmt.Println("first class")
default:
fmt.Println("keep going")
}
// THE loop. Shape 1 -- classic counting:
for i := 1; i <= 3; i++ {
fmt.Println("attempt", i)
}
// Shape 2 -- for as "while": keep the condition, drop the rest.
retries := 3
for retries > 0 {
retries--
}
fmt.Println(retries) // 0
// Shape 3 -- for range: walk a collection, index and value together.
scores := []int{72, 89, 91}
total := 0
for i, s := range scores {
fmt.Println(i, s)
total += s
}
fmt.Println(total / len(scores)) // 84 -- integer division, exact here
// Bonus shape (Go 1.22+): range over a plain integer.
for range 3 {
fmt.Print("go ")
}
fmt.Println()
}
Now the personality trait you met in section 02: Go treats an unused variable or
unused import as a compile error. This feels harsh for about a day. The reasoning:
unused code is either a bug (you meant to use it) or clutter (you forgot to delete it), and
in a codebase with four hundred contributors, clutter compounds. The same philosophy powers
gofmt, the formatter that ships in the toolchain: there is exactly
one Go style — tabs, brace placement, spacing, all of it — and every Go codebase on
earth is formatted identically. Nobody argues about style in Go code review, ever, because
there is nothing to argue about. Opinionated tooling is Go's answer to a thousand tiny team
frictions.
This program's logic is flawless. What happens when you run it?
package main
import (
"fmt"
"os"
)
func main() {
sum := 0
for i := 1; i <= 10; i++ {
sum += i
}
message := "the sum is"
fmt.Println(sum)
}
Reveal the answer
It never runs. The compiler stops it cold, with this real output:
$ go run predict2.go
./predict2.go:5:2: "os" imported and not used
./predict2.go:13:2: declared and not used: message
Two errors: the unused os import and the unused message
variable. Not warnings — errors. Delete both lines and it prints 55. When
you genuinely must discard a value, Go gives you the blank identifier _ —
an explicit, visible shrug — which you'll use constantly from section 05 on.
05 · Core GoFunctions — Multiple Returns and the defer Statement
Go functions hold two ideas you won't find bundled this way anywhere else. First,
multiple return values as a first-class, everyday idiom — a function
can simply return two things, no wrapper objects, no out-parameters. This is the load-bearing
wall of the whole language: "a result, plus whether it worked" comes back as an honest pair,
and section 06 builds Go's entire error philosophy on it. Second, defer:
"run this call when the surrounding function returns, however it returns" — which lets
cleanup live next to the setup it cleans up after.
// Run with: go run functions.go
package main
import (
"fmt"
"os"
"strings"
)
// MULTIPLE RETURN VALUES -- the single most Go-shaped feature there is.
// No out-parameters, no wrapper objects: just return two things.
func divide(a, b int) (int, bool) {
if b == 0 {
return 0, false // can't divide -- and the caller can SEE that
}
return a / b, true
}
// Named returns: the signature itself documents what comes back.
// Use sparingly -- nice for short functions, confusing in long ones.
func minMax(nums []int) (min, max int) {
min, max = nums[0], nums[0]
for _, n := range nums {
if n < min {
min = n
}
if n > max {
max = n
}
}
return // returns the named min and max
}
// Variadic: call with any number of ints; they arrive as a slice.
func sum(nums ...int) int {
total := 0
for _, n := range nums {
total += n
}
return total
}
func main() {
q, ok := divide(10, 3)
fmt.Println(q, ok) // 3 true
_, ok = divide(1, 0)
fmt.Println(ok) // false -- _ discards the value we don't need
lo, hi := minMax([]int{7, 2, 9, 4})
fmt.Println(lo, hi) // 2 9
fmt.Println(sum(1, 2, 3, 4)) // 10
// Functions are VALUES: assign them, pass them, return them.
shout := strings.ToUpper
fmt.Println(shout("go")) // GO
apply := func(f func(string) string, s string) string { return f(s) }
fmt.Println(apply(shout, "quiet")) // QUIET
// DEFER: "run this when the surrounding function returns -- however
// it returns." Cleanup lives NEXT TO setup, and can never be forgotten.
f, err := os.Create("demo.txt")
if err != nil {
fmt.Println("create failed:", err)
return
}
defer os.Remove("demo.txt") // deferred calls run LIFO:
defer f.Close() // ...so Close runs first, THEN Remove. Right order, free.
fmt.Fprintln(f, "defer keeps cleanup next to setup")
fmt.Println("wrote demo.txt")
// LIFO order, demonstrated:
for i := 1; i <= 3; i++ {
defer fmt.Println("deferred", i)
}
fmt.Println("main body done")
// main body done / deferred 3 / deferred 2 / deferred 1 -- then the
// file closes and the demo file vanishes, in exactly the right order.
}
Sit with the two defer lines after os.Create. In most languages,
opening a file here and remembering to close it there — down every early
return, past every error path — is a chore that generations of programmers have gotten wrong.
defer collapses the distance to zero: open, and on the very next line, schedule
the close. Deferred calls stack up and run last-in, first-out when the
function exits, which naturally unwinds resources in reverse order of acquisition — close the
file, then delete it. You will meet defer again guarding waitgroups in
section 09 and recovering from panics in section 06.
One subtlety hides in defer. What does this print?
package main
import "fmt"
func main() {
x := 1
defer fmt.Println("deferred sees", x)
x = 99
fmt.Println("body sees", x)
}
Reveal the answer
body sees 99, then deferred sees 1. The rule: a deferred
call's arguments are evaluated at the moment of the defer statement; only the
call itself waits until the function returns. x was 1 when the defer line
ran, so 1 is what was captured. This exact question is an interview classic — and the
practical rule is: defer computes its arguments now, runs later.
06 · The philosophyErrors Without Exceptions — Failure as a Value
Here is Go's most debated design decision, and the one that most defines reading real Go
code. Most languages handle failure with exceptions: an error thrown here abandons
normal execution and teleports to a catch block somewhere up the call chain —
possibly three files away, possibly nowhere. Go looked at that and made the opposite bet:
an error is just a value, returned from the function like any other
result, using the multiple returns you just learned. The idiom that fills every Go codebase
on earth:
// Run with: go run errors.go
package main
import (
"errors"
"fmt"
"os"
"strconv"
)
// A SENTINEL error: a named value callers can test for with errors.Is.
var ErrNotFound = errors.New("book not found")
func findShelf(isbn string) (int, error) {
shelves := map[string]int{"978-0134190440": 12}
shelf, ok := shelves[isbn]
if !ok {
// %w WRAPS the cause: context grows, the original survives inside.
return 0, fmt.Errorf("findShelf %q: %w", isbn, ErrNotFound)
}
return shelf, nil
}
func parseMarks(raw string) (int, error) {
n, err := strconv.Atoi(raw) // string -> int; may fail
if err != nil {
return 0, fmt.Errorf("parseMarks %q: %w", raw, err)
}
if n < 0 || n > 100 {
return 0, fmt.Errorf("parseMarks: %d out of range", n)
}
return n, nil
}
func main() {
// THE shape of Go error handling. Failure is a value, handled in
// plain sight, exactly where it happens -- not teleported to a
// catch block three files away.
marks, err := parseMarks("78")
if err != nil {
fmt.Println("error:", err)
os.Exit(1)
}
fmt.Println("marks:", marks) // marks: 78
if _, err := parseMarks("many"); err != nil {
fmt.Println("error:", err)
// The whole causal chain prints, because each layer wrapped with %w.
}
// errors.Is walks the wrapped chain looking for a specific VALUE:
if _, err := findShelf("978-0000000000"); errors.Is(err, ErrNotFound) {
fmt.Println("that book simply isn't in the catalog")
}
// errors.As digs for a specific TYPE, to reach its fields:
var numErr *strconv.NumError
if _, err := parseMarks("many"); errors.As(err, &numErr) {
fmt.Println("the unparseable input was:", numErr.Num)
}
// panic/recover exists -- for the truly broken, not for control flow.
defer func() {
if r := recover(); r != nil {
fmt.Println("recovered from:", r)
}
}()
var books []string
_ = books[5] // indexing past the end is a BUG, so Go panics
fmt.Println("never reached")
}
Run it and read the second error carefully:
parseMarks "many": strconv.Atoi: parsing "many": invalid syntax. That's the
whole causal chain in one line — each layer added its context with
fmt.Errorf("...: %w", err), and the original error survived inside, still
testable with errors.Is (match a specific error value) or
errors.As (extract a specific error type). Wrapping-with-context is
how experienced Go teams turn a 2 a.m. log line into a diagnosis.
The honest trade-off, stated fairly, because interviewers probe exactly this. The
cost of Go's choice is verbosity: if err != nil appears thousands of
times in a real codebase, and yes, it reads repetitively. The purchase is
visibility: every single point where failure can occur is marked in the code, greppable,
reviewable — there is no invisible control flow, no "which of these five lines can throw?"
Exceptions optimize for the writer's happy path; error values optimize for the reader tracing
a failure — and code is read far more than written, at team scale for years. And
panic? It's for the truly broken — indexing past the end of a list, a
nil map write, an impossible state. The Go proverb is "crash, don't handle": a panicking
program fails loudly at the bug instead of limping on with corrupted state.
recover exists for the rare boundary (a server keeping one bad request from
killing the process) — not as a catch block for everyday errors.
Section 04 said Go refuses to compile an unused variable. So… can you silently
ignore an error? What happens if you write marks, _ := parseMarks("many")
— or just call a function and discard everything?
Reveal the answer
It compiles. _ is a legal, deliberate shrug — and a plain call like
f.Close() with its error unexamined compiles too. Go's guarantee is that
errors are visible, not that they're handled: the compiler forces
acknowledgment of returned values only when you bind them to names. Teams close the gap
with go vet and linters like errcheck that flag discarded
errors. The mature take: _ on an error is an auditable decision you
can grep for — which is still a world better than an exception nobody caught.
07 · The heart of GoStructs, Methods & Interfaces — Composition Over Ceremony
Go has no classes and no inheritance — deliberately. It builds programs from three smaller pieces instead. A struct bundles named fields into one value. A method is a function attached to a type via a receiver. And an interface is a small contract that types satisfy implicitly — the big idea of the section. Structs first, because they force us to meet pointers — gently:
// Run with: go run structs.go
package main
import "fmt"
// A struct: named fields bundled into one value. That's the whole
// definition -- no constructors, no inheritance, no "class".
type Student struct {
ID string
Name string
Marks int
}
// A METHOD is a function with a RECEIVER -- the (s Student) part.
// VALUE receiver: the method works on a COPY. Reads are fine; writes vanish.
func (s Student) Describe() string {
return fmt.Sprintf("%s %s (%d)", s.ID, s.Name, s.Marks)
}
// POINTER receiver: the method works on the ONE real struct -- writes stick.
// Rule of thumb: method needs to modify, or struct is big? Pointer receiver.
func (s *Student) UpdateMarks(marks int) {
s.Marks = marks
}
func main() {
// Struct literals: zero-valued, or (best practice) field-named.
var blank Student // zero value: {"" "" 0} -- usable immediately
s := Student{ID: "S-101", Name: "Asha", Marks: 78}
fmt.Println(blank.Marks, s.Describe()) // 0 S-101 Asha (78)
// Pointers, gently: & takes an address, * follows one. That's all.
p := &s // p points AT s. No copy was made.
p.Marks = 80 // Go follows the pointer for you: same as (*p).Marks
fmt.Println(s.Marks) // 80 -- s itself changed, because p SHARES it
copyOf := s // plain assignment COPIES the whole struct
copyOf.Marks = 99
fmt.Println(s.Marks, copyOf.Marks) // 80 99 -- two independent structs
s.UpdateMarks(83) // Go takes &s for you when calling a pointer method
fmt.Println(s.Describe()) // S-101 Asha (83)
}
Pointers deserve one calm paragraph, because the fear around them belongs to C, not Go.
A pointer answers a single question: when I hand this struct to something, do I hand a
copy (changes stay private) or do I share the one original
(changes stick)? copyOf := s copies; p := &s shares. That's the
entire decision. There is no pointer arithmetic in Go, the garbage collector frees memory for
you, and a forgotten pointer can't dangle. Draw it once and it stays drawn:
&s makes a second name for one struct; plain assignment makes a second struct. Value vs pointer receivers are this same choice, written into the method.| Question | Value receiver (s Student) | Pointer receiver (s *Student) |
|---|---|---|
| Do writes stick? | No — the method edits a copy | Yes — the method edits the original |
| Copy cost per call | The whole struct | One machine word |
| Choose when… | Small struct, read-only method (Describe) | Method mutates, or struct is large (UpdateMarks) |
| House rule | If any method needs a pointer receiver, give the type pointer receivers everywhere — consistency beats micro-optimization | |
Now the big idea. In Java, a class must announce implements Notifier to
satisfy an interface — a declared, compile-time allegiance. Go removes the announcement:
if your type has the methods, it satisfies the interface. Full stop.
That one rule inverts who owns the contract — the consumer of a dependency declares
the small interface it needs, and any type anywhere satisfies it without ever knowing the
interface exists:
// Run with: go run interfaces.go
package main
import (
"fmt"
"strings"
)
// An interface: a small contract -- just method signatures. Notice what's
// MISSING below: no type ever declares "implements Notifier". If you have
// the method, you satisfy the interface. That's the whole rule.
type Notifier interface {
Notify(msg string) string
}
type EmailNotifier struct{ Address string }
type SMSNotifier struct{ Number string }
func (e EmailNotifier) Notify(msg string) string {
return "email to " + e.Address + ": " + msg
}
func (s SMSNotifier) Notify(msg string) string {
return "sms to " + s.Number + ": " + strings.ToUpper(msg)
}
// "Accept interfaces, return structs": this function works with every
// Notifier that exists today -- and every one anyone writes NEXT YEAR,
// in packages this file will never import or know about.
func alertAll(ns []Notifier, msg string) {
for _, n := range ns {
fmt.Println(n.Notify(msg))
}
}
func main() {
alertAll([]Notifier{
EmailNotifier{Address: "asha@example.com"},
SMSNotifier{Number: "98765-43210"},
}, "deploy finished")
}
This is why Go interfaces stay small. The standard library's most famous one,
io.Reader, has exactly one method — Read — and because
satisfaction is implicit, files, network connections, HTTP bodies, compressors, and string
buffers all satisfy it without coordinating with each other. The working idiom is
"accept interfaces, return structs": take the smallest contract you need as
a parameter, hand back the concrete thing you made. And Go's answer to inheritance is
embedding, which deserves exactly one paragraph: put a type name
inside a struct with no field name — type LoudNotifier struct { SMSNotifier } —
and the inner type's fields and methods are promoted, callable directly on the outer
type. It looks like inheritance, but it's honest composition: the inner value is really
there, you can reach it as loud.SMSNotifier, and there's no fragile override
hierarchy — Go shops build big things by composing small ones.
Receivers meet the copy rule. What does this print?
package main
import "fmt"
type Counter struct{ N int }
func (c Counter) Bump() { c.N++ }
func main() {
c := Counter{}
for range 3 {
c.Bump()
}
fmt.Println(c.N)
}
Reveal the answer
0. Bump has a value receiver, so each call
incremented a fresh copy of the struct, which evaporated at the method's end — three
bumps, three discarded copies, original untouched. Change the receiver to
(c *Counter) and it prints 3. This is the single most common
beginner Go bug, and it's Fig. E12.2 wearing a method's clothing.
08 · Core GoSlices & Maps — The Two Containers That Run Everything
Go ships two workhorse containers, and between them they cover most programs ever
written. An array in Go has its length baked into its type
([3]int and [4]int are different types), which makes raw arrays
rare in daily code. The everyday tool is the slice: a small
header — a pointer into a backing array, a length, and a capacity —
that gives you a growable, shareable view of data. Understanding that header is
understanding slices, so here's the picture before the code:
// Run with: go run slices.go
package main
import "fmt"
func main() {
// An ARRAY's length is part of its type -- [3]int and [4]int are
// different types. You'll rarely touch arrays directly...
arr := [3]int{10, 20, 30}
fmt.Println(arr, len(arr)) // [10 20 30] 3
// ...because the everyday tool is the SLICE: a small header
// (pointer, length, capacity) pointing into a backing array.
scores := []int{72, 89, 91}
fmt.Println(len(scores), cap(scores)) // 3 3
// append grows the slice. When capacity runs out, Go allocates a
// BIGGER backing array and copies -- watch cap jump:
scores = append(scores, 65)
fmt.Println(len(scores), cap(scores)) // 4 6 -- roughly doubled
// Slicing makes a VIEW, not a copy: same backing array, shared.
week := []int{1, 2, 3, 4, 5, 6, 7}
weekend := week[5:7] // elements 5 and 6
weekend[0] = 60
fmt.Println(week) // [1 2 3 4 5 60 7] -- the edit shows through BOTH
// MAPS: Go's hash table. make() one, then use it.
stock := make(map[string]int)
stock["978-0134190440"] = 3
stock["978-0136820109"] = 0
// A missing key returns the ZERO VALUE -- no crash, no null. But then
// "missing" and "stored zero" look identical... enter the COMMA-OK idiom:
fmt.Println(stock["nope"]) // 0 -- missing, silently
count, ok := stock["978-0136820109"]
fmt.Println(count, ok) // 0 true -- really stored, really zero
delete(stock, "978-0134190440")
fmt.Println(len(stock)) // 1
// Go has no set type. The idiom: map[string]bool.
issued := map[string]bool{"978-0134190440": true}
fmt.Println(issued["978-0134190440"], issued["nope"]) // true false
}
Three details worth pinning. append returns a new slice header — always
write scores = append(scores, x), because when capacity runs out Go allocates a
bigger backing array (watch cap jump from 3 to 6) and your old header would
still point at the old one. The comma-ok idiom — v, ok := m[key]
— is zero values coming home to roost: since a missing key returns a perfectly usable 0,
the second return value is how you ask "was it really there?". You'll meet the same idiom on
channels. And map iteration order is deliberately randomized — Go shuffles
it at runtime so no one can accidentally depend on it. If you need order, sort the keys;
the language just refuses to let "worked in the demo" become a hidden contract.
The slice header meets spare capacity. What does this print?
package main
import "fmt"
func main() {
a := make([]int, 3, 5) // length 3, capacity 5
b := append(a, 99)
a = append(a, 42)
fmt.Println(b[3])
}
Reveal the answer
42 — not 99. Capacity was 5, so neither append reallocated:
both wrote into spare slot 3 of the same backing array. b's append
wrote 99 there; a's append then overwrote it with 42, and b[3]
sees the overwrite. Two headers, one array — Fig. E12.3 again, now with teeth. The
production rule: never keep two slices appending into shared capacity; copy when in
doubt.
09 · The headlineConcurrency — Goroutines, Channels, and the Kitchen at Full Service
This is the section Go is famous for, and the reason it owns the infrastructure layer.
A goroutine is a function call with go in front:
go worker() — that's the entire API for "run this concurrently". Goroutines are
not operating-system threads: they're tiny (stacks start at a couple of KB and grow
on demand), the Go runtime schedules them itself, and launching a hundred thousand
is a normal Tuesday where a hundred thousand OS threads would be an outage. The mechanism
behind that claim is the interview differentiator, and it lives in
Under the hood. But goroutines alone are just parallel chaos — the
kitchen needs the serving hatch. A channel is a typed pipe:
one goroutine sends (ch <- v), another receives (v := <-ch),
and the data moves — Go's proverb is "don't communicate by sharing memory; share
memory by communicating". Here is the pattern that appears, in some costume, in every Go
service ever deployed — workers fanning out, results fanning in:
// Run with: go run workers.go
package main
import (
"fmt"
"sync"
"time"
)
// A worker: pull jobs from one channel until it closes, push results
// into another. It neither knows nor cares how many siblings it has.
func worker(id int, jobs <-chan int, results chan<- string, wg *sync.WaitGroup) {
defer wg.Done() // §05's defer: "I'm finished", guaranteed on every exit
for j := range jobs {
time.Sleep(10 * time.Millisecond) // pretend this is real work
results <- fmt.Sprintf("worker %d finished job %d", id, j)
}
}
func main() {
jobs := make(chan int) // unbuffered: each send waits for a receiver
results := make(chan string, 9) // buffered: room for 9 without waiting
var wg sync.WaitGroup
for id := 1; id <= 3; id++ {
wg.Add(1)
go worker(id, jobs, results, &wg) // `go` = run concurrently. That's it.
}
for j := 1; j <= 9; j++ {
jobs <- j // the three workers race to pull these
}
close(jobs) // tells every `range jobs` loop: no more work coming
wg.Wait() // block here until all three workers call Done
close(results) // now safe -- nobody will send again
for r := range results {
fmt.Println(r)
}
}
Run it and you'll see all nine jobs finish, interleaved across the three workers in a
different order each run — concurrency, visibly. Note the channel arrow types in the worker's
signature (<-chan receive-only, chan<- send-only): the
compiler enforces the direction data flows. The unbuffered vs buffered
distinction matters enough for interviews to make it explicit: an unbuffered channel
(make(chan int)) is a rendezvous — the send literally waits until a
receiver takes the value, synchronizing the two goroutines at that moment. A buffered channel
(make(chan string, 9)) is a small mailbox — sends complete immediately until the
buffer fills, decoupling the two sides. And sync.WaitGroup is the roll-call:
Add before launching, defer wg.Done() inside, Wait to
block until everyone's finished.
Two more tools complete the professional kit. select waits on several channel
operations at once and takes whichever is ready first — which turns timeouts, cancellation,
and multiplexing into four-line patterns. And context.Context is the parameter
every real Go API takes first — the standard way a caller says "you
have 50 milliseconds" or "the user hung up; stop working". Open any serious Go codebase, any
cloud SDK, any database driver: the first parameter is a context. Here are both, honestly
small:
// Run with: go run timeout.go
package main
import (
"context"
"fmt"
"time"
)
// The signature every real Go API shares: context first. The context is
// how the CALLER says "you have 50ms" or "the user hung up -- stop".
func slowQuery(ctx context.Context, d time.Duration) (string, error) {
select {
case <-time.After(d): // the "query" finishing after d
return "42 rows", nil
case <-ctx.Done(): // the caller giving up -- cancellation is a channel
return "", ctx.Err()
}
}
func main() {
// A context with a deadline. cancel releases its resources -- defer it.
ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
defer cancel()
// select waits on SEVERAL channel operations at once and takes
// whichever is ready first. That one keyword is timeouts, cancellation,
// and multiplexing -- the heart of every Go network service.
if rows, err := slowQuery(ctx, 10*time.Millisecond); err == nil {
fmt.Println("fast query:", rows) // beats the deadline
}
if _, err := slowQuery(ctx, 10*time.Second); err != nil {
fmt.Println("slow query:", err) // the deadline wins
}
}
Output: fast query: 42 rows, then slow query: context deadline
exceeded — the ten-second "query" was cut off at the deadline, because
ctx.Done() is itself just a channel that closes when time's up, and
select heard it first. Cancellation flows down the call tree through that one
parameter — which is exactly how a cancelled HTTP request stops the database query it
triggered, three layers down.
Last, the safety net. Concurrency's classic failure is the data race — two goroutines touching the same variable, at least one writing, with no coordination. Go ships a detector in the toolchain:
// Run twice: go run race.go (works... probably... sometimes)
// go run -race race.go (the truth)
package main
import (
"fmt"
"sync"
)
func main() {
counter := 0
var wg sync.WaitGroup
for range 1000 {
wg.Add(1)
go func() {
defer wg.Done()
counter++ // 1000 goroutines, one variable, no lock: a data race
}()
}
wg.Wait()
fmt.Println(counter) // often NOT 1000 -- increments got lost
}
Three plain runs on the author's test machine printed 986,
987, 977 — increments silently lost as goroutines overwrote each
other. With -race, the runtime names the crime scene
(WARNING: DATA RACE … race.go:17) and exits with status 66. The fixes, in
order of preference: restructure so the data flows through a channel (each goroutine
sends its increment); or guard the variable with sync.Mutex; or use
sync/atomic for bare counters. Professional Go teams run their entire test
suite under -race in CI — and so will your lab.
| Tool | Choose when | Avoid when |
|---|---|---|
go + channels | Data flows between stages — pipelines, worker pools, fan-in | You're just protecting one shared counter (that's a mutex/atomic job) |
sync.WaitGroup | You must wait for N goroutines to finish | You also need their outputs — pair it with a results channel, as workers.go does |
select | Several channels at once; timeouts; cancellation | Only one channel and no deadline — plain receive reads better |
sync.Mutex / atomic | Shared state updated in place (caches, counters) | The design could pass ownership through a channel instead |
context.Context | Deadlines and cancellation crossing API boundaries — always first parameter | Smuggling business data around — it's for control flow, not cargo |
Before reading on: in workers.go, delete the
close(jobs) line. What happens — wrong output, a hang, or something
louder?
Reveal the answer
Something louder. The workers' for j := range jobs loops only end when
the channel closes — so all three sit blocked on a receive that will never come, none
ever calls Done, and main blocks forever in wg.Wait(). With
every goroutine asleep, the Go runtime detects it and kills the program:
fatal error: all goroutines are asleep - deadlock! — with a stack dump
showing main in WaitGroup.Wait and each worker in chan receive
(real output from the author's test run). Moral: closing a channel is how the sender
says "no more" — forget it, and downstream waits forever. In production, where
other goroutines keep the process alive, this same bug doesn't crash — it
silently leaks goroutines. That's the leak from the hook's interview.
10 · ToolingModules, Tests, and the Cross-Compilation Party Trick
Everything so far ran as single files with go run — deliberately, so the
language never hid behind tooling. Real projects add exactly one ceremony:
go mod init <name> creates go.mod, the project manifest that
names your module and pins your dependencies (go mod tidy keeps it synced with
what your code actually imports). After that, the whole professional workflow is subcommands
of the one go binary you already own:
# One project, one manifest, zero configuration files beyond it:
mkdir gradebook && cd gradebook
go mod init example.com/gradebook # creates go.mod -- the project manifest
go test ./... # find and run every *_test.go in the project
gofmt -l . # list files not in THE Go style (empty output = clean)
go vet ./... # catch "compiles but wrong": bad Printf verbs, lock misuse...
go mod tidy # sync go.mod with what the code actually imports
go build . # produce the single binary
# The ops party trick: cross-compile by setting two environment variables.
GOOS=windows GOARCH=amd64 go build -o app.exe . # a Windows .exe, built on Linux
GOOS=darwin GOARCH=arm64 go build -o app-mac . # an Apple-silicon macOS binary
# Verified on the author's Linux test machine, `file` reports:
# app.exe -> PE32+ executable (console) x86-64, for MS Windows
# app-mac -> Mach-O 64-bit arm64 executable
Read that last block again, because it's the payoff of Fig. E12.1: from one Linux laptop,
Go produced a genuine Windows executable and a genuine Mac binary — no virtual machines, no
extra toolchains, two environment variables. This is why single-binary Go tools (Docker's
CLI, Terraform, kubectl) install by downloading one file, and why ops teams reach
for Go by reflex. Now the testing idiom — the one Go code reviews genuinely enforce. Tests
live in _test.go files next to the code; the house style is the
table-driven test: a slice of cases, one loop, one assertion:
package gradebook
import "fmt"
// Grade maps marks to a letter grade -- value + error, the shape from §06.
func Grade(marks int) (string, error) {
switch {
case marks < 0 || marks > 100:
return "", fmt.Errorf("marks out of range: %d", marks)
case marks >= 90:
return "A", nil
case marks >= 60:
return "B", nil
default:
return "C", nil
}
}
package gradebook
import "testing"
// THE Go testing idiom: the table-driven test. One slice of cases, one
// loop, one assertion. Adding a case is one line -- which is exactly why
// Go code reviews ask for these.
func TestGrade(t *testing.T) {
tests := []struct {
name string
marks int
want string
wantErr bool
}{
{"distinction", 95, "A", false},
{"boundary hit", 90, "A", false},
{"middle", 78, "B", false},
{"low", 12, "C", false},
{"impossible", 108, "", true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := Grade(tt.marks)
if (err != nil) != tt.wantErr {
t.Fatalf("Grade(%d) error = %v, wantErr %v", tt.marks, err, tt.wantErr)
}
if got != tt.want {
t.Errorf("Grade(%d) = %q, want %q", tt.marks, got, tt.want)
}
})
}
}
$ go test -v ./...
=== RUN TestGrade
=== RUN TestGrade/distinction
=== RUN TestGrade/boundary_hit
=== RUN TestGrade/middle
=== RUN TestGrade/low
=== RUN TestGrade/impossible
--- PASS: TestGrade (0.00s)
--- PASS: TestGrade/distinction (0.00s)
--- PASS: TestGrade/boundary_hit (0.00s)
--- PASS: TestGrade/middle (0.00s)
--- PASS: TestGrade/low (0.00s)
--- PASS: TestGrade/impossible (0.00s)
PASS
ok example.com/gradebook 0.005s
Each table row becomes a named subtest — a failure tells you which case broke,
and adding coverage for a new edge is one line in the slice. No test framework to choose, no
assertion library to install: go test is in the box, like everything else.
There are no dumb questions
- Where are my classes? Is Go even object-oriented?
- Go has objects (struct values with methods) but deliberately no classes, no inheritance, and no hierarchy. The designers watched twenty years of deep inheritance trees turning into fragile lasagna and chose composition instead: small structs, small interfaces satisfied implicitly, embedding when you want reuse. Teams coming from Java report the same arc: two weeks of "where's my AbstractFactoryBase?", then relief.
- Isn't
if err != nileverywhere just… tedious? - Somewhat, yes — Go engineers joke about it too, and the honest answer keeps both halves: you pay three lines per failure point, and in exchange every failure point in the entire codebase is visible, greppable, and reviewable. For infrastructure software — where the failure paths ARE the product — that trade wins. Editors snippet it; you'll stop noticing within a week.
- Does Go have generics?
- Yes — since Go 1.18 (2022):
func Map[T, U any](xs []T, f func(T) U) []U. Notice, though, that this entire primer needed them zero times — that's representative. You'll read generics in library code (including the slices and maps stdlib packages) long before you need to write any. Learn to read the[T any]brackets, and defer writing them until a real duplication problem asks. - Go or Rust for infrastructure work?
- Both live at the infrastructure layer; they sit at different points on the control-vs-velocity dial. Go: garbage-collected, learnable in days, compile times in seconds — it optimizes for teams shipping network services. Rust: no GC, memory safety proven at compile time, a famously steep learning curve — it wins where every microsecond and allocation counts (kernels, browsers, database engines, the hottest serving paths). Most platform teams are Go-first with Rust for the hot 5%. Chapter E13 maps this properly.
- Do I have to manage memory like in C? The pointers worried me.
- No. Go pointers answer one question — share or copy (Fig. E12.2) — and that's where
the resemblance to C ends. There's no pointer arithmetic, no
free(), no dangling pointers: the garbage collector reclaims what's unreachable, and the compiler even decides stack-vs-heap placement for you (see Under the hood). You get the sharing semantics without the footguns.
11 · Watch it breakThe Fresher-Classic Gotchas, Demonstrated
Six traps, one runnable file, every output real. Two of them panic on purpose — and
the file catches those panics with the recover pattern from section 06, so
the tour keeps moving. Each of these is simultaneously a bug you will write and a
screening question you will be asked; run the file once and you're inoculated on both
fronts. (The seventh classic — unused imports and variables refusing to compile — already
ambushed you in section 04's Brain Power.)
// Run with: go run gotchas.go
package main
import (
"fmt"
"time"
)
// Runs f, catching any panic so the tour can continue -- recover exactly
// as taught in §06: for the truly broken, which these deliberately are.
func safely(name string, f func()) {
defer func() {
if r := recover(); r != nil {
fmt.Println(name, "panicked:", r)
}
}()
f()
}
func main() {
// GOTCHA 1 -- the nil map. Declared but never make()d. Reading is
// fine (zero values!), which lulls you... then a write PANICS.
safely("gotcha 1", func() {
var stock map[string]int
fmt.Println(stock["missing"]) // 0 -- reading a nil map: fine
stock["new"] = 1 // writing: boom
})
// GOTCHA 2 -- slice aliasing: a slice of a slice is a WINDOW, not a
// copy. Mutations show through every window onto the array.
orig := []int{1, 2, 3, 4, 5}
view := orig[1:3]
view[0] = 99
fmt.Println(orig) // [1 99 3 4 5] -- orig changed. Surprise.
// GOTCHA 3 -- the subtle follow-up: append can silently BREAK the
// aliasing. Exceed capacity, and view moves to a fresh array.
view = append(view, 6, 7, 8) // needs 5 slots, cap is 4 -> reallocates
view[0] = -1 // edits the NEW array only
fmt.Println(orig[1], view[0]) // 99 -1 -- the link is gone. Silently.
// GOTCHA 4 -- shadowing: := inside a block creates a NEW variable
// that dies at the closing brace. The outer one never changed.
config := "default"
if override := true; override {
config := "from flags" // NEW config, shadows the outer one
fmt.Println("inside if:", config)
}
fmt.Println("after if:", config) // default -- the "assignment" vanished
// GOTCHA 5 -- HISTORICAL: the loop-variable capture. Before Go 1.22
// all three goroutines shared ONE i and typically printed "3 3 3".
// Since Go 1.22 (Feb 2024), each iteration gets a FRESH i -- fixed.
done := make(chan bool)
for i := 0; i < 3; i++ {
go func() {
fmt.Print(i, " ") // Go 1.22+: 0 1 2 (order varies)
done <- true
}()
}
for range 3 {
<-done
}
fmt.Println()
// GOTCHA 6 -- a nil CHANNEL blocks forever. Not an error, not a
// panic: the receive below would simply never, ever complete.
var ch chan int // declared, never made -- nil
select {
case v := <-ch:
fmt.Println("got", v) // unreachable until the end of time
case <-time.After(100 * time.Millisecond):
fmt.Println("gave up: a nil channel blocks forever")
}
}
$ go run gotchas.go
0
gotcha 1 panicked: assignment to entry in nil map
[1 99 3 4 5]
99 -1
inside if: from flags
after if: default
2 0 1
gave up: a nil channel blocks forever
Walk the output against the file. The nil map read handed back a friendly 0, then the
write panicked — the fix is always make(map[string]int) (or a literal) before
writing. Gotchas 2 and 3 are Fig. E12.3's two acts: slicing shares the backing array (edit
visible through both), then append outgrew capacity, quietly moved
view to a new array, and the sharing stopped — the nastiest version of
this bug is code that behaves differently depending on how full a slice happened to be.
Gotcha 4 is the shadowing trap — the := inside the block minted a brand-new
config that died at the brace (go vet and linters catch most real
cases, typically when an err gets shadowed). Gotcha 5 printed
2 0 1 — three distinct values, because Go 1.22 fixed the historical
loop-variable capture; before 2024 this printed 3 3 3 and was the
single most-asked Go gotcha. Interviewers still ask it, so know both eras: pre-1.22, one
shared i; 1.22+, a fresh i per iteration. And gotcha 6: a nil
channel doesn't error — it blocks forever, a goroutine leak in its purest form, which is
why the demo needed select plus a timeout just to escape it.
12 · Under the hoodThe Scheduler and the GC, If You Want Them
Optional depth — but this is where "I've used Go" becomes "I understand Go" in an interview. Start with the claim from section 09: a hundred thousand goroutines is normal, a hundred thousand OS threads is an outage. Why? An OS thread costs a megabyte-scale stack reserved up front, plus a trip into the kernel every time you switch between threads. A goroutine starts with a stack of just a few kilobytes that grows and shrinks on demand, and switching goroutines is a cheap user-space operation inside the Go runtime. The runtime then multiplexes your many goroutines onto a small pool of OS threads — an M:N scheduler:
Goroutines vs OS threads — the numbers behind the interview answer
The comparison that anchors a strong answer, in three measurable gaps.
Memory: an OS thread reserves a stack measured in megabytes (commonly
~1–8 MB); a goroutine starts at kilobytes (historically 2 KB; recent runtimes
size the start dynamically, still single-digit KB) and its stack grows and shrinks
as needed — so 100,000 goroutines cost hundreds of MB where 100,000 threads would want
hundreds of GB of address space and crush the kernel scheduler. Switch
cost: switching threads means a kernel context switch (microseconds, caches
disturbed); switching goroutines is a user-space register swap by the runtime
(nanoseconds-to-tens-of-ns). Blocking: when a goroutine blocks on a
channel or a network read, the runtime parks the G and hands its M the
next runnable G — network I/O rides an event loop (netpoller) under the hood, so ten
thousand idle connections don't hold ten thousand threads hostage. The P layer (one per
CPU by default, GOMAXPROCS) exists so run queues are mostly per-core with
work-stealing between them. One caveat worth volunteering: goroutines are cheap, not
free — leaking them (section 09's Brain Power) is Go's version of a memory leak, and
real dashboards graph goroutine counts for exactly that reason.
Go's garbage collector and escape analysis — optional depth
Go's GC in one honest paragraph: it's a concurrent mark-sweep collector engineered for one goal above all — tiny pauses. It marks reachable objects while your goroutines keep running, stopping the world only for sub-millisecond blips, and it is deliberately non-generational: no Eden, no survivor spaces, no promotion. If you read Chapter E1's tour of the JVM's generational heap, the contrast is a genuine design fork: the JVM bets on sophisticated heap organization (paying occasional bigger pauses, buying raw throughput); Go bets on simplicity plus a second trick — escape analysis — that keeps many objects off the heap entirely. The compiler proves at build time whether a value can outlive its function: if not, it lives on the goroutine stack and is freed for free when the function returns; only values that "escape" (get returned by pointer, stored globally, captured by a goroutine) are heap-allocated at all. Less garbage created means less garbage to collect. And you can watch the decision happen:
// Ask the compiler where things live: go build -gcflags=-m escape.go
package main
import "fmt"
type Student struct {
Name string
Marks int
}
func makeStudent(name string) *Student {
s := Student{Name: name, Marks: 0}
return &s // s outlives the function -> the compiler moves it to the heap
}
func localOnly() int {
s := Student{Name: "temp", Marks: 50}
return s.Marks // s never escapes -> stack, freed for free on return
}
func main() {
fmt.Println(makeStudent("Asha").Name, localOnly())
}
Real compiler output from the author's test machine includes the money line
./escape.go:12:2: moved to heap: s — the returned-by-pointer Student
escaped, the local-only one didn't. You never manage this; you can always inspect it.
The interview one-liner: "Go's GC is concurrent, low-pause, and non-generational — and
escape analysis means a lot of allocation never reaches the heap in the first
place."
13 · The road aheadWhere Go Fits in a Backend Career
Straight talk, same as every chapter: you will probably not write your company's core business services in Go — for most of this track that layer is Java and Spring (E4–E7). Go owns the layer underneath. Docker (E9), Kubernetes (E10), and Terraform — the machinery those services deploy onto — are Go programs. Prometheus, which scrapes their metrics, and Grafana, which draws them, are Go programs. Caddy and Traefik, the proxies in front of them, are Go. CockroachDB is Go. And when a team needs an API gateway — the traffic layer from E7 that authenticates, routes, rate-limits, and logs every request — Go is a default choice, because single-binary deploys, instant startup, and one goroutine per request are exactly that job's shape. Writing a small gateway, a Kubernetes operator, or an internal CLI in Go is a classic platform-team project — and a strong portfolio piece for the "platform engineer" postings that list Go by name. Consuming a vendor SDK from Go looks like this — the example uses one hosted API's official Go SDK, but every well-built SDK has the same shape, and this one compiles as shown against the current version:
// Setup: go mod init askclaude && go get github.com/anthropics/anthropic-sdk-go
// Run: go run . (reads ANTHROPIC_API_KEY from the environment)
package main
import (
"context"
"fmt"
"os"
"github.com/anthropics/anthropic-sdk-go"
)
func main() {
client := anthropic.NewClient() // finds ANTHROPIC_API_KEY on its own
// context first -- §09's habit, and every serious Go SDK's contract.
message, err := client.Messages.New(context.Background(), anthropic.MessageNewParams{
Model: "claude-opus-5", // $5 / $25 per 1M tokens, Aug 2026
MaxTokens: 16000,
Messages: []anthropic.MessageParam{
anthropic.NewUserMessage(anthropic.NewTextBlock(
"Explain goroutines to a fresher in three sentences.")),
},
})
if err != nil { // the same two lines that guard every call in this primer
fmt.Println("request failed:", err)
os.Exit(1)
}
// The reply is a slice of typed content blocks -- a type switch (§07's
// interfaces at work) picks out the text ones.
for _, block := range message.Content {
switch variant := block.AsAny().(type) {
case anthropic.TextBlock:
fmt.Println(variant.Text)
}
}
}
Notice that the SDK is your curriculum: a context as the first parameter (§09),
a struct literal with field names (§07), a slice of message values (§08), the
value, err := guard (§06), and a type switch over an interface (§07). Nothing
in professional Go is a new language — it's these ten hours, composed.
The platform-engineering pitch, in stakeholder language: "Go teams build the paved roads every other team drives on — the deploy pipelines, the gateways, the monitoring stack. The runtime math is direct: a Go service ships as one small file, so containers shrink from hundreds of megabytes to tens, cold starts drop from seconds to milliseconds, and one box handles tens of thousands of concurrent connections — that's a hosting bill and an autoscaling story, not a style preference. And the platform twist: gateways, proxies, operators and infrastructure tooling are being written in Go and Rust right now, which is why 'platform engineer' postings list Go by name. Ten hours of Go buys an engineer a seat at the infrastructure table where backend systems actually get operated."
14 · The lablinkcheck — The Classic Go Project, Done Properly
The concurrent link checker is to Go what the library manager is to Java: the canonical first project, because it exercises the language's whole personality — files, HTTP, worker pools, timeouts, and the race detector. Here's your starter: a complete, working, sequential checker (~80% of the plumbing). It checked four URLs in 3.1 seconds on the author's test machine, because it waits out each slow URL one at a time. Your 20% is making it concurrent — the checklist below.
// STARTER -- the sequential version. Your 20%: make it concurrent.
// Setup: mkdir linkcheck && cd linkcheck && go mod init linkcheck
// Run: go run . urls.txt
package main
import (
"bufio"
"fmt"
"net/http"
"os"
"strings"
"time"
)
type result struct {
URL string
Status int // HTTP status code, or 0 if the request failed outright
Err error
}
// normalizeURL is the PURE helper your table-driven tests will cover:
// trim whitespace, skip blanks and #comments, default the scheme.
func normalizeURL(line string) (string, bool) {
line = strings.TrimSpace(line)
if line == "" || strings.HasPrefix(line, "#") {
return "", false
}
if !strings.Contains(line, "://") {
line = "https://" + line
}
return line, true
}
func check(client *http.Client, url string) result {
resp, err := client.Get(url)
if err != nil {
return result{URL: url, Err: err}
}
defer resp.Body.Close()
return result{URL: url, Status: resp.StatusCode}
}
func main() {
if len(os.Args) < 2 {
fmt.Println("usage: linkcheck <urls-file>")
os.Exit(1)
}
f, err := os.Open(os.Args[1])
if err != nil {
fmt.Println("open:", err)
os.Exit(1)
}
defer f.Close()
client := &http.Client{Timeout: 3 * time.Second}
var results []result
scanner := bufio.NewScanner(f)
for scanner.Scan() {
url, ok := normalizeURL(scanner.Text())
if !ok {
continue
}
results = append(results, check(client, url)) // one at a time -- slow!
}
for _, r := range results {
if r.Err != nil {
fmt.Printf("FAIL %s (%v)\n", r.URL, r.Err)
} else {
fmt.Printf("%4d %s\n", r.Status, r.URL)
}
}
}
The offline path — no internet required. This tiny server (the standard library's
net/http, whole thing in ~20 lines) gives you a guaranteed 200, a guaranteed
404, and a route slow enough to trip any timeout. Save it in its own folder and run
it in a second terminal:
// The offline path: a tiny local server, so the lab needs no internet.
// Save in its OWN folder, run in a second terminal: go run testserver.go
package main
import (
"fmt"
"net/http"
"time"
)
func main() {
http.HandleFunc("/ok", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "all good")
})
http.HandleFunc("/missing", func(w http.ResponseWriter, r *http.Request) {
http.NotFound(w, r) // a guaranteed 404
})
http.HandleFunc("/slow", func(w http.ResponseWriter, r *http.Request) {
time.Sleep(10 * time.Second) // guaranteed to trip your timeout
fmt.Fprintln(w, "finally")
})
fmt.Println("test server on http://localhost:8077")
// ListenAndServe blocks forever -- if it ever returns, it's an error.
fmt.Println(http.ListenAndServe(":8077", nil))
}
# urls.txt -- lab targets: the local test server, plus one dead port
http://localhost:8077/ok
http://localhost:8077/missing
http://localhost:8077/slow
http://localhost:9999/nothing-listens-here
$ time go run . urls.txt
200 http://localhost:8077/ok
404 http://localhost:8077/missing
FAIL http://localhost:8077/slow (Get "http://localhost:8077/slow": context deadline exceeded ...)
FAIL http://localhost:9999/nothing-listens-here (... connect: connection refused)
real 0m3.1s <- sequential: the slow URL held everyone hostage
Mission: turn the sequential starter into a concurrent checker with a bounded worker pool — the workers.go pattern from §09, doing real work. Every construct appears because the job demands it.
- Concurrency: a jobs channel of URLs, a fixed pool of 4 worker goroutines, a results channel, and a
sync.WaitGroup— bounded, so 10,000 URLs never means 10,000 simultaneous requests - Per-request timeout via context: build each request with
http.NewRequestWithContextusing acontext.WithTimeoutof 2s (replacing the client-wide timeout) —/slowmust FAIL fast, not hang the pool - Aggregate all results, then sort by status code before printing (
sort.Slice— errors as status 0 first, then 200s, 404s…) - Table-driven tests for
normalizeURLinlinkcheck_test.go— at least five cases: blank line, comment, bare host, already-schemed URL, surrounding whitespace;go test ./...passes go run -race . urls.txtreports zero races, andgo vet ./...is clean- Measure and record the win in a README line: sequential vs concurrent wall time on the same urls.txt (starter: 3.1s; the pool should land near the single slowest response — under 1.5s here)
- Graceful failure everywhere: missing file, unreachable host, malformed URL — the program reports and continues; it never panics
Stretch: prove the single-binary story — GOOS=windows GOARCH=amd64 go build
(or darwin/arm64), copy the artifact to another machine or a FROM scratch
container, and watch it run with nothing installed. Second stretch: add a
-workers N flag with the standard library's flag package and
chart checked-URLs-per-second as N grows.
15 · Interview radarThe Go Canon
The Go interview canon is short and stable — these seven cover the screening round at nearly every platform team. You've now run all of them; what follows is the shape of a strong answer, not a script.
"Goroutines vs threads?"
The real test Whether you give the scheduler answer, with numbers — not just "goroutines are lightweight."
Strong answer An OS thread reserves a megabyte-scale stack and switches via the kernel. A goroutine starts at a few KB with a stack that grows on demand, switches in user space, and the runtime multiplexes goroutines M:N onto a small thread pool — so a blocked goroutine parks a cheap G, not a thread. That's why 100K goroutines is routine and 100K threads is an outage.
Land it Volunteer the caveat: cheap isn't free — goroutine leaks are Go's memory leak.
"Unbuffered vs buffered channels?"
Strong answer An unbuffered channel is a rendezvous: the send blocks until a receive takes the value, so it also synchronizes the two goroutines. A buffered channel is a mailbox of size N: sends complete until it's full, which decouples producer from consumer at the cost of that synchronization.
Land it Strong close: buffers smooth bursts, they don't fix a consumer that's slower on average — that's backpressure, and unbuffered channels give it to you for free.
"Slices vs arrays — and what does append really do?"
Strong answer An array is a fixed-size value. A
slice is a three-word header — pointer, len, cap — over a backing array.
append writes in place while capacity remains; when it runs out,
it allocates a bigger array, copies, and returns a header pointing there. That
is why you always reassign the result, and why two slices can share an array
until an append silently divorces them.
Land it Demonstrate gotchas 2–3 from memory and the follow-ups end.
"Implicit interfaces vs Java's implements?"
Strong answer Mechanics first: a type satisfies a
Go interface by having the methods — there is no declaration. Then the payoff,
which is decoupling: the consumer defines the small interface it
needs, the way io.Reader is one method, and any type in any
package satisfies it without importing it. That's how packages compose without
coordinating.
Land it Close with the idiom: accept interfaces, return structs.
"Error values vs exceptions — defend Go's choice."
Strong answer State the trade honestly. The cost
is if err != nil repetition; the purchase is that every failure
path is visible, local, and greppable — no invisible control flow. Then add the
professional layer: wrap with fmt.Errorf("%w") so the chain tells
a story, test with errors.Is/As, and reserve panic for genuine
bugs — "crash, don't handle."
Land it Presenting it as a trade-off, not a religion, is the differentiator.
"What does defer do — and when are its arguments evaluated?"
Strong answer A deferred call runs when the
surrounding function returns by any path, and deferred calls stack LIFO, so
resources unwind in reverse acquisition order. The everyday uses are
f.Close(), wg.Done(), mu.Unlock(), and
recover().
Land it Volunteer the trap: arguments are evaluated at the defer statement, not at return — which is why predict3 prints the old value.
"What did Go 1.22 change about loop variables?"
Strong answer This is the historical classic.
Before 1.22, one i was shared across iterations, so goroutines
launched in a loop famously all saw the final value — the "3 3 3" bug. Since
Go 1.22, released February 2024, each iteration gets a fresh variable, and that
bug class is gone.
Land it Knowing both eras — and
saying "fixed in 1.22" unprompted — signals your Go is current, exactly like
knowing why old blog posts still write i := i inside loops.
16 · RecapWhat You Can Do Now
- You can write, run, and explain a complete Go program — every word of
package main,import, andfunc main(), plus why the capital letter is the visibility system - You can tell the single-binary story with evidence:
go build, a ~2 MB static file, and a cross-compiled Windows .exe built on Linux with two env vars - You can use zero values,
:=vsvar, and the comma-ok idiom on purpose — and explain why Go has no undefined and no truthiness - You can handle failure the Go way:
value, errreturns, wrapping with%w,errors.Is/As, and panic reserved for the truly broken — and defend the trade-off against exceptions fairly - You can choose value vs pointer receivers with a rule, not a guess — and draw the share-vs-copy picture that decides it
- You can explain implicit interfaces as a decoupling mechanism and use "accept interfaces, return structs" in real code
- You can draw a slice header, predict aliasing and append-reallocation behavior, and demonstrate all six gotchas from memory with their real outputs
- You can build the worker-pool pattern — goroutines, channels, WaitGroup, select, context — and prove it race-free with
-race - You can give the M:N scheduler answer with numbers, and the one-paragraph GC + escape-analysis story, in an interview
From this chapter: close the page and rebuild workers.go
from an empty file — jobs channel, three workers, WaitGroup, close, drain — then run it
and check against section 09. If you can do that cold, you own Go concurrency at the
fresher-interview level and most of the lab besides. And two
cross-references: open Chapter E13 next to see where Go sits among every language
this track touches — the map makes the "infrastructure layer" claim precise. Then revisit
the Distributed Systems primer's distributed-systems refresher and reread its queue-and-worker patterns
knowing that goroutines and channels are exactly how Go shops implement every one of
them — the language and the architecture are the same picture at two zoom levels.