Bitpath

Go: Zero to Hero

Start from your very first line of code and work up to goroutines, channels and a real program, in a language where almost everything is spelled out. Every snippet is real Go that compiles and runs, and no earlier programming is assumed.

  • Beginner
  • 8 units, 24 lessons, 312 exercises
  • Go
  • No experience needed

Unit 01 · 3 lessons

First steps

Read a small Go program, predict what it prints, and store values in variables

  1. > start01Values and expressions
  2. 02Variables and types
  3. BOSSA receipt
Unit prize
  1. 01
    Values and expressions

    The frame of a Go program, printing, numbers, text and arithmetic.

  2. 02
    Variables and types

    Names for values, the four basic types, and converting between them on purpose.

  3. BOSS
    A receipt

    Prices, a discount and tax become a formatted total, and the compiler gets a say.

Read the unit guide

A program is a list of instructions. Go runs them one at a time, from the top line to the bottom line, and each fmt.Println shows something on the screen. Every Go program has the same frame: package main, an import for the tools it borrows, and func main() { ... } around the instructions. The lessons show only the lines inside main.

Text in double quotes is a string and is printed exactly as written. Numbers have no quotes and can be calculated with: +, -, *, /. Times and divide go before plus and minus, unless brackets say otherwise. Dividing two whole numbers gives a whole number (7 / 2 is 3), and % gives the remainder (7 % 2 is 1).

A variable is a name for a value. count := 3 creates one; count = 5 changes one that exists. var count int creates one that starts at its zero value. const makes a name that can never change.

Every value has a type: int for whole numbers, float64 for numbers with a decimal point, string for text, bool for true or false. Go never mixes types by itself. To multiply a float64 by an int you convert on purpose: price * float64(qty).

Before it runs anything, Go compiles the file: it checks every line and refuses to start if one breaks the rules. A compiler error names the file, the line and the problem, as in ./main.go:7:10: undefined: subtotl. Go to that line first. The classic first errors are a misspelt name, two types mixed in one sum, and a variable that is created and never used.

fmt.Printf prints to a pattern: %d is a gap for a whole number, %.2f for a decimal number with two decimals, %s for a string, and \n ends the line. That is how 8.4 becomes 8.40 on a receipt.

Unit 02 · 3 lessons

Decisions and loops

Make a program choose with if and switch, repeat with for, and trace both by hand

  1. 01Conditions
  2. 02Loops
  3. BOSSFizzBuzz and friends
Unit prize
  1. 01
    Conditions

    Comparisons, if and else, and, or and not, and switch.

  2. 02
    Loops

    One word, for, in three forms; running totals; tracing a loop by hand.

  3. BOSS
    FizzBuzz and friends

    Loops and conditions together: FizzBuzz, digit sums, primes and the off-by-one error.

Read the unit guide

An if asks a yes-or-no question and runs the lines in its braces only when the answer is true. The questions are comparisons: ==, !=, <, >, <=, >=. Each gives a bool. Remember the double sign: == compares, a single = stores.

Questions combine: a && b is true only if both are, a || b if at least one is, and !a flips the answer. In a chain of if, else if, else, Go asks from the top and runs the first branch that is true, and only that one. So the most specific question goes first. A switch does the same job for one value against a list of cases, and it also runs one case only.

A loop repeats lines, and in Go every loop is a for. With one question, for n > 0 { ... }, it repeats while the answer is true. With three parts, for i := 0; i < 3; i++ { ... }, it counts: a start, a question before every pass, a step after every pass. With nothing, for { ... }, it runs until a break. continue skips to the next pass.

The way to understand a loop is to trace it: write down every variable after every pass, like a table. Check the first pass and the last pass with extra care. Most loop bugs are off-by-one errors: < where <= was meant, or a start at 1 that should be 0.

Three patterns come back all the time. A running total: create sum := 0 before the loop and add inside it. A remainder test: n%3 == 0 means "n divides evenly by 3". Taking a number apart: n % 10 is the last digit and n / 10 removes it.

Something inside a loop must change the thing its question looks at. If nothing does, the loop never ends.

Unit 03 · 3 lessons

Functions and errors

Write small functions with typed inputs and results, and report failure as a value

  1. 01Defining functions
  2. 02Errors as values
  3. BOSSA text toolkit
Unit prize
  1. 01
    Defining functions

    Parameters, results, return against print, several results, and scope.

  2. 02
    Errors as values

    A result and an error, checking err, strconv.Atoi, and why ignoring an error is the bug.

  3. BOSS
    A text toolkit

    Three small functions on text: a palindrome check, a vowel counter and a Caesar shift.

Read the unit guide

A function is a named piece of work. func area(w, h int) int says: the name is area, it takes two int parameters, and it gives back an int. A call such as area(3, 4) runs the function with those values and is then replaced by what it returns. main is a function too: the one Go runs first.

return hands a value back to the caller and ends the function at once. That is different from printing, which only shows a value on the screen. A function that promises a result must return one on every path, or the compiler says "missing return". A function can return several values: func divmod(a, b int) (int, int).

Each function has its own private names. A variable created inside one does not exist outside it, and a parameter is a copy of the value that was passed: changing the copy changes nothing for the caller. This is called scope.

Go has no special machinery for things going wrong. A function that can fail returns its result and an error. The error is nil when all went well. The caller checks straight away: n, err := strconv.Atoi(s), then if err != nil { ... }. Make errors with errors.New("...") or, when the message needs a value in it, fmt.Errorf("bad age: %d", age).

Never use the result before checking the error. When Atoi fails it still returns a number, 0, and a program that ignores the error carries on with a wrong answer that looks right. Go helps a little: an unused err variable does not compile, so you must check it or throw it away on purpose with _.

A string can be read one position at a time: len(s) is its length and s[i] is the byte at position i, counting from 0. A byte is a small number that stands for a character, and 'a' in single quotes is such a number, so letters can be compared and calculated with. Check every function you write against answers you already know, including at least one case for each possible result.

Unit 04 · 3 lessons

Collections

Keep many values under one name with slices and maps, and loop over them with range

  1. 01Slices
  2. 02Maps and strings
  3. BOSSA word counter
Unit prize
  1. 01
    Slices

    Indexes, len, append, range, slicing, and two names that share one row of values.

  2. 02
    Maps and strings

    Values found by key, the comma-ok lookup, delete, no fixed order, bytes and runes.

  3. BOSS
    A word counter

    Split a text into words, count them in a map, sort the keys and report the most common.

Read the unit guide

A slice is a row of values of one type: []int{4, 8, 15}. s[i] reads or replaces the value at index i, counting from 0, and len(s) is the number of values, so the last index is len(s)-1. Asking for an index that does not exist stops the program with "index out of range".

append adds to the end and hands back the longer slice: always write s = append(s, x). for i, v := range s walks a slice and gives the index and the value on each pass; write _ for the one you do not need.

A slice is a small handle that points at its values. b := a copies the handle, and a[1:3] makes a window onto the same values, so a change through one name shows through the other. An array, with its size in the type like [3]int, is different: it has a fixed length and is copied when assigned.

A map stores pairs of key and value: map[string]int. Create one with make or with braces, set an entry with m[key] = v, remove one with delete(m, key). Looking up a missing key gives the zero value; the form v, ok := m[key] also tells you whether the key was there. A map declared with var alone is nil, and storing into it crashes.

A map has no order. range visits every pair once, but in a different order from run to run. For a fixed order, collect the keys into a slice and sort it with sort.Strings.

Strings are stored as bytes: len and s[i] count bytes, and a character such as é takes two. A whole character is a rune. range over a string goes rune by rune, and []rune(s) gives a slice of runes. The classic counting pattern uses a map: counts[w]++ adds one to the entry for w, starting from zero if it is new.

Unit 05 · 3 lessons

Structs and pointers

Build your own types from fields, give them methods, and share one value with a pointer

  1. 01Structs
  2. 02Pointers and methods
  3. BOSSAn inventory
Unit prize
  1. 01
    Structs

    Group related values into one type of your own, and learn when Go copies it.

  2. 02
    Pointers and methods

    Change a value through a pointer, and attach functions to your types.

  3. BOSS
    An inventory

    A shop's stock as a slice of structs, changed safely through methods.

Read the unit guide

A struct is a type you design yourself. It groups values that belong together under one name: type Item struct { Name string; Price int }. You make one with a literal, Item{Name: "tea", Price: 4}, and reach its fields with a dot: it.Price. Fields you leave out start at their zero value.

Structs are copied. b := a gives b its own copy of every field, and a function that takes an Item works on a copy too. The loop variable in for _, it := range items is also a copy. Changing a copy never changes the original. This is the bug to remember from this unit: an update that silently disappears.

A pointer is the fix. &x means "where x lives", *int is the type "pointer to an int", and *p is the value at the other end. A function that takes *Item and is called with &tea changes the caller's item. A pointer that points nowhere is nil, and following it stops the program with a panic.

A method is a function attached to a type. The receiver, written before the name, says which type: func (it Item) Value() int. You call it with a dot: tea.Value(). With a value receiver the method gets a copy. With a pointer receiver, func (it *Item) Remove(n int), it gets the original and can change it. Go takes the address for you, so you still write tea.Remove(2).

Rule of thumb: if a method changes the value, give it a pointer receiver. To change the items inside a slice, go through the index (inv[i].Stock++), not through the loop variable.

Unit 06 · 3 lessons

Interfaces and errors

Write code that works for any type with the right methods, and treat failure as a value with detail

  1. 01Interfaces
  2. 02Errors in depth
  3. BOSSA bank
Unit prize
  1. 01
    Interfaces

    Describe what a value can do, and write one function for many types.

  2. 02
    Errors in depth

    Errors with data inside, errors wrapped in context, defer and panic.

  3. BOSS
    A bank

    Accounts and transfers where every rule is a method that can say no.

Read the unit guide

A struct says what a value is made of. An interface says what a value can do: it is a list of methods. type Shape interface { Area() int } means "anything with an Area() int method". A type fits an interface simply by having the methods. You never declare it; Go checks it for you.

That lets one function serve many types. A function that takes a Shape works for squares, rectangles and types nobody has written yet. fmt.Println uses the same trick: if your type has a String() string method (the fmt.Stringer interface), that method decides how it prints. any is the interface with no methods, so every value fits, and a type switch, switch v := x.(type), asks what is really inside.

error is an interface too: anything with an Error() string method. So an error can be your own struct carrying details, or one named value such as var ErrFunds = errors.New("insufficient funds") that callers can test for.

Errors gather context on the way up. fmt.Errorf("pay: %w", err) wraps an error: new message outside, original inside. Because of the wrapping, test with errors.Is(err, ErrFunds), not ==, and use errors.As to pull a struct error back out and read its fields.

defer schedules a call for the moment the surrounding function returns, on every path out, which makes it the home of clean-up code. A panic is Go's emergency stop, for bugs such as an index past the end. Things that can go wrong in normal use, like bad input or a missing file, are returned as errors instead.

The pattern of the bank boss is the pattern of most Go programs: data in structs, rules in methods with pointer receivers, a check before every change, and an error returned when the rule says no.

Unit 07 · 3 lessons

Real programs

Split code into packages, lean on the standard library, and prove your code works with tests

  1. 01Packages and the standard library
  2. 02Tests, JSON and generics
  3. BOSSA log report
Unit prize
  1. 01
    Packages and the standard library

    How Go code is organised, and the library packages you will use every day.

  2. 02
    Tests, JSON and generics

    Check your code with tests, exchange data as JSON, and write one function for several types.

  3. BOSS
    A log report

    Turn raw lines of text into a ranked report, with tests.

Read the unit guide

Go code lives in packages. A package is a folder of files that share one package line, and a module is a folder of packages with a go.mod file that gives it a name. Inside a package every name is visible. From outside, only names that start with a capital letter are: bank.New can be called, a field called balance cannot even be seen. That is how a package protects its rules.

The standard library is a set of packages that come with Go. strings splits, joins and trims text. strconv turns text into numbers and back, and returns an error when the text is not a number. sort orders slices: sort.Ints and sort.Strings for simple ones, sort.Slice with a small function for everything else. time handles durations and dates.

A test is code that checks code. It lives in a file ending in _test.go, in a function TestXxx(t *testing.T), and go test runs them all. The Go habit is the table-driven test: a slice of cases, each an input and the wanted result, and one loop over them. A failing test means the code and the expectation disagree; you decide which is wrong.

encoding/json moves data in and out of your program. json.Marshal turns a struct into JSON text, json.Unmarshal fills a struct from it (hand it a pointer), and field tags such as json:"name" choose the names. Only exported fields take part. Unmarshal returns an error when the data does not fit.

A generic function is written once for several types: func Largest[T int | string](xs []T) T. The part in square brackets names a type parameter and says which types are allowed, and the compiler only lets the body do what all of those types can do.

Most small programs have the shape of the log report: read text, parse each line into a struct, count or group in a map, copy the map into a slice, sort, print.

Unit 08 · 3 lessons

Hero

Run work at the same time with goroutines, and coordinate it with WaitGroups, mutexes and channels

  1. 01Goroutines
  2. 02Channels
  3. BOSSA task runner
Unit prize
  1. 01
    Goroutines

    Start work on the side with go, wait for it, and keep shared data safe.

  2. 02
    Channels

    Pass values between goroutines through pipes that keep them in step.

  3. BOSS
    A task runner

    A whole concurrent program: a pool of workers, errors collected, results in order.

Read the unit guide

A goroutine is a function running at the same time as the rest of your program. You start one by writing go in front of a call. Goroutines are cheap, so programs start them by the thousand. The catch: go does not wait and gives nothing back, and when main returns the program ends, whether the goroutines have finished or not.

So every go needs an answer to "how will I know it is done?". A sync.WaitGroup is one answer: Add(1) before starting each goroutine, defer wg.Done() inside it, and wg.Wait() where you need them all finished.

When goroutines share a variable and at least one of them changes it, you have a data race: updates get lost, and the result differs from run to run. A sync.Mutex lets one goroutine at a time into the guarded stretch between Lock and Unlock.

A channel is the other answer, and the one Go prefers. It is a typed pipe: ch <- v sends, v := <-ch receives. On a plain channel each side waits for the other, so a channel passes a value and keeps the two goroutines in step at once. A buffered channel, make(chan int, 3), holds a few values before a send has to wait. The sender calls close(ch) to say "no more", which ends a range over the channel. select waits on several channels and takes whichever is ready first.

If every goroutine is waiting for another one, nothing can ever happen, and Go stops the program: "all goroutines are asleep - deadlock!". Read it as a question: who was supposed to send, receive, unlock or close?

The task runner puts it all together: tasks go into a channel, a few workers take them out and send results back, and main collects, sorts and reports. You started this course with fmt.Println; you are ending it with a concurrent program. Next: the Go roadmap covers the same language at speed and goes on to cancelling work with context, pipelines and an HTTP service.

Learn Go: Zero to Hero on your phone.

Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.

One email when Bitpath is ready to try. Nothing else. Privacy