Go
Learn Go by reading and fixing small programs that really compile: values and slices, interfaces and errors, goroutines and channels, then tests and an HTTP service. Written for someone fluent in another language, with Python as the point of comparison.
- Beginner
- 4 units, 12 lessons, 156 exercises
- Go
- Builds on one other language
Unit 01 · 3 lessons
The basics
Read and write small Go programs with values, slices, maps and structs
- 01Values and functions
Declarations, zero values, strict types, several results, one loop.
- 02Slices and maps
Arrays copy, slices share, append may move, maps answer twice.
- BOSSStructs and methods
Build a small inventory from structs, pointers and methods.
Read the unit guide
Go is a small language on purpose. There is one loop (for), one way to format code, no classes and no exceptions. Most of what you know from Python has a direct counterpart; this unit is about the places where the counterpart behaves differently.
Every type has a zero value: 0, "", false, or nil for slices, maps and pointers. A declared variable is always usable, so there is no None check for an int. The price is that "missing" and "zero" look the same, which is why map lookups come with a second result, ok.
The compiler is strict where Python is relaxed. Types never convert on their own, an unused local variable or import stops the build, and a function that promises a value must return on every path. Treat each error as a note about one line.
Arrays and structs are values: assigning one copies it. Slices and maps are small handles onto shared storage: assigning one copies the handle. A slice is a pointer, a length and a capacity, and append writes into the shared array while there is room. Always keep what append returns.
A struct groups fields, and a method is a function with a receiver in front of its name. A value receiver works on a copy; a pointer receiver (*Item) can change the original. There is no pointer arithmetic: a pointer only says "this one, not a copy of it".
Unit 02 · 3 lessons
Types and errors
Describe behaviour with interfaces and handle failure as ordinary values
- 01Interfaces
Satisfied without saying so, kept small, and never quite nil.
- 02Errors
Return them, check them, wrap them, and save panic for bugs.
- BOSSOrganising a program
Packages, generics and embedding, fitted into one program.
Read the unit guide
An interface is a list of methods. A type satisfies it by having those methods, and never says so: there is no implements. It is Python's duck typing, checked by the compiler. The useful interfaces are tiny: fmt.Stringer, io.Reader, io.Writer and error have one method each.
An interface value holds two things: the concrete type and the value. any is the interface with no methods, so it holds anything, and a type assertion (v.(string)) or a type switch gets the concrete value back out. An interface is nil only when both halves are empty, which is why a nil pointer stored in an error is not a nil error.
Failure is a value too. A function that can fail returns an error last, and the caller checks if err != nil on the spot. Add context with fmt.Errorf("...: %w", err), then ask errors.Is for a particular error or errors.As for a particular type anywhere in the chain.
defer runs a call when the function returns, whichever way it returns, so cleanup sits next to setup. panic is for bugs, not for a missing file; recover exists so that one bad request does not take a whole server down.
Programs are organised in packages: one directory, one package, and a capital letter exports a name. Generics let one function work for many types, with a constraint saying what the type must support. Embedding reuses a type by placing it inside another. It is composition, not inheritance: the inner type never learns about the outer one.
Unit 03 · 3 lessons
Concurrency
Run work in goroutines and coordinate it with WaitGroups, mutexes, channels and contexts
- 01Goroutines
Start work with go, wait with a WaitGroup, guard data with a Mutex.
- 02Channels
Pipes that block: send, receive, close, range and select.
- BOSSA worker pool
Fan out, fan in, chain stages, cancel, and untangle a deadlock.
Read the unit guide
A goroutine is a function running concurrently with the rest of the program, started by putting go in front of a call. Goroutines are cheap enough to start by the thousand. The catch: go returns nothing and waits for nothing, and when main returns the program ends, finished or not.
There are two ways to coordinate. The first is shared memory with locks: a sync.WaitGroup counts goroutines so you can wait for them, and a sync.Mutex lets one goroutine at a time touch shared data. Two goroutines using one variable without a lock, where at least one writes, is a data race, and its result is undefined.
The second is channels: typed pipes. A send on an unbuffered channel blocks until a receiver takes the value, so a channel passes data and synchronises at once. A buffered channel holds a few values before a send blocks. The sender closes a channel to say "no more", which ends a range over it. select waits on several channel operations and takes whichever is ready.
Go's slogan is "share memory by communicating": give a value to one goroutine at a time through a channel instead of guarding it with locks. Worker pools and pipelines are that idea with a few more channels.
Every blocked goroutine is waiting for another one. If all of them are waiting, the runtime stops the program with "all goroutines are asleep - deadlock!" and prints where each one is stuck. Read that trace as a list of who waits for whom. To stop work early, pass a context.Context and have each goroutine watch ctx.Done().
Unit 04 · 3 lessons
Real programs
Use the standard library, test your code, and build an HTTP service you can check without a network
- 01The standard library
Strings, conversions, sorting, time and JSON without a dependency.
- 02Tests and tools
Table-driven tests, go test, benchmarks, vet, gofmt and modules.
- BOSSAn HTTP service
Handlers, routes, JSON and middleware, tested without a port.
Read the unit guide
Most Go programs need few dependencies, because the standard library covers the everyday work. Strings have no methods: the functions live in the strings package, and strconv converts between text and numbers, returning an error when the text is bad. sort and slices order things. time.Duration is a number of nanoseconds that prints itself readably.
encoding/json maps JSON onto structs. Only exported fields take part, and a field tag such as json:"name" chooses the key. Marshal returns bytes; Unmarshal needs a pointer to fill, ignores keys it does not know, and leaves fields alone when their key is absent.
Testing is built in. A file ending in _test.go holds functions named TestXxx(t *testing.T), and go test runs them. The usual style is table-driven: a slice of cases and one loop. Benchmarks use the same tool, gofmt settles formatting, go vet flags suspicious code, and go.mod records the module path and dependency versions. Real Go code is indented with tabs by gofmt; these lessons show two spaces to fit a phone.
An HTTP handler is a function of a ResponseWriter and a *Request. Handlers are normally top-level functions; the snippets here store them in variables only to keep the lines short. A ServeMux routes patterns like GET /items/{id} to handlers. The response is written in order: headers, then the status code, then the body, and the first write to the body sends status 200 if you have not chosen one.
Middleware is a function that takes a handler and returns a new one that does something before or after calling it. And because a handler is only a function, the httptest package can call it with a fake request and a recorder: the whole service is tested without opening a port.
Learn Go on your phone.
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.