Learnings

Go, part 5 of 5

Go Practice: Exercises with Solutions

25 exercises that drill the concepts of the four earlier Go pages, from FizzBuzz to a race-free bank and a small JSON API. Each one gives the task and the exact expected output, a few hints, and a hidden solution with its real output from Go 1.27.

How to use this page

Part 1 of 5 · setup and the exercise list

Read the task, write the program yourself, and open the solution only after you have something that runs or you are stuck.

The routine for each exercise

How to use this page

Give every exercise its own folder and module, so programs never clash and you can keep them as a reference.

  • Try for 10 to 15 minutes before opening a solution. Being stuck for a while is what makes the solution stick.
  • Match the expected output exactly. Every solution prints the same text, so diff works if you save both.
  • Predict-the-output puzzles have no task to code: write your answer down, then open the solution. These are the ones interviewers like.
  • Compare, do not copy. If your version differs, check the "what to notice" bullets: they name the idiom the exercise is about.

All exercises at a glance

How to use this page

Easy, medium and hard are relative to someone who has just read the concept pages. The last column names the page that explains the concept.

#ExerciseLevelDrillsConcept page
1FizzBuzz with a switcheasyfor, tagless switchgo-basics.html
2Reverse a stringeasybytes vs runesgo-basics.html
3Remove duplicates in ordereasymap as a set, appendgo-basics.html
4Word frequencyeasymaps, sorting, cmpgo-basics.html
5Two-summediummap lookup, multiple returnsgo-basics.html
6Account id generatormediumclosuresgo-basics.html
7Slice aliasing puzzlemediumlen, cap, shared arraysgo-basics.html
8Defer order puzzlemediumdefer, named resultsgo-basics.html
9Rupees with Stringereasymethods, fmt.Stringergo-types.html
10Account with a sentinel erroreasystructs, %w, errors.Isgo-types.html
11Receiver bug huntmediumvalue vs pointer receivers, range copiesgo-types.html
12Notifier interfacemediuminterfaces, type switchgo-types.html
13Nil interface puzzlemediuminterface values, typed nilgo-types.html
14Transfer errorshardcustom error types, wrapping, errors.Asgo-types.html
15Map, Filter, Reducehardgenerics, constraints, ~go-types.html
16Parallel sum of squareseasygoroutines, WaitGroupgo-concurrency.html
17Fix the data raceeasyrace detector, mutex, atomicgo-concurrency.html
18Pipelinemediumchannels, close, rangego-concurrency.html
19Ordered worker poolmediumfan-out, fan-in, result ordergo-concurrency.html
20Timeout and cancelmediumselect, contextgo-concurrency.html
21Spot the goroutine leakhardblocked senders, buffered channelsgo-concurrency.html
22Concurrent bank transfershardper-account locks, lock ordering, invariantsgo-concurrency.html
23Bank ledger with testsprojectinterfaces, errors, table-driven testsgo-setup.html, go-types.html
24LRU cacheprojectcontainer/list, maps, pointersgo-basics.html, go-types.html
25JSON API for accountsprojectnet/http, JSON, mutex, httptestgo-types.html, go-concurrency.html

Basics

Part 2 of 5 · exercises for go-basics.html

Strings, slices, maps, closures and defer. Exercises 7 and 8 are predict-the-output puzzles.

1. FizzBuzz with a switch

Basics · easy

Print the numbers 1 to 15 on one line separated by spaces, replacing multiples of 3 with Fizz, multiples of 5 with Buzz and multiples of both with FizzBuzz. Use a switch, not an if/else chain.

Hints

  • A switch with no expression after it tests each case as a boolean.
  • Cases are checked top to bottom and the first true one wins.
  • strconv.Itoa turns an int into its decimal string.
Solution
  • The n%15 case must come first. Go cases do not fall through, so there is no break to forget.
  • make([]string, 0, 15) sets the capacity up front, so append never reallocates.

2. Reverse a string

Basics · easy

Write reverse(s string) string that works for any text, not only ASCII. Reverse "héllo, 世界" and also print its length in bytes and in characters (runes).

Hints

  • A Go string is bytes. Reversing the bytes breaks every character that takes more than one byte.
  • Convert to []rune first, then swap from both ends.
  • Look at unicode/utf8 for counting.
Solution
  • len(s) counts bytes: é is 2 bytes and each Chinese character is 3. Python's len counts code points, so this surprises Python developers.
  • slices.Reverse(r) does the swap loop for you. Neither handles combining marks (an e followed by U+0301), which need grapheme segmentation.

3. Remove duplicates in order

Basics · easy

Write dedupe(in []string) []string that keeps the first occurrence of each value and preserves the original order, in one pass. Print the result for b a b c a d and for an empty slice.

Hints

  • Go has no set type. A map with an empty value type does the job.
  • Sorting first would lose the order, so do not sort.
Solution
  • struct{} takes zero bytes, which is why map[T]struct{} is the idiomatic set. map[T]bool also works and reads more easily.
  • slices.Compact only removes adjacent duplicates, so it is not the answer here. The loop is O(n) time and O(n) extra space.

4. Word frequency

Basics · easy

Count the words in "The cat and the hat and THE bat", ignoring case. Print one word per line, most frequent first, and break ties alphabetically so the output is the same on every run.

Hints

  • strings.Fields splits on any run of whitespace.
  • Map iteration order is random by design. Collect the keys and sort them.
  • slices.SortFunc takes a compare function that returns a negative, zero or positive int.
Solution
  • counts[w]++ works on a missing key because a missing key reads as the zero value. That is Python's Counter without the import.
  • cmp.Or returns its first non-zero argument, which makes multi-key sorts one expression.

5. Two-sum

Basics · medium

Write twoSum(nums []int, target int) (int, int, bool) that returns the indexes of two numbers adding up to target, in O(n). For [2 7 11 15] try targets 9, 26 and 100.

Hints

  • For each number you need to know, instantly, whether its complement has been seen.
  • Store value to index in a map as you go, not before the loop.
  • Use the comma-ok form to tell "not found" from "found at index 0".
Solution
  • Checking before inserting stops a number from pairing with itself.
  • Without comma-ok, seen[x] returns 0 for a missing key, which is also a valid index. This is the bug interviewers look for.

6. Account id generator

Basics · medium

Write newIDGen(prefix string, start int) func() string. Each call of the returned function gives the next id. Create one generator for savings accounts (SB, from 1001) and one for current accounts (CA, from 5001), and show they count independently.

Hints

  • The returned function can read and change a variable declared in newIDGen.
  • Each call of newIDGen creates a fresh variable.
Solution
  • The closure keeps next alive after newIDGen returns; the compiler moves it to the heap. Python needs nonlocal for the same thing.
  • It is not safe for concurrent use. Two goroutines calling savings() race on next; use atomic.Int64 if that matters.

7. Slice aliasing puzzle

Basics · medium, predict the output

Write down the three lines this program prints before you open the answer.

Hints

  • Write down len and cap of b, c and d.
  • append writes in place when there is spare capacity, and copies to a new array when there is not.
Solution
  • Line 1: b has len 2, cap 4, so append writes 99 into a[2]. Both see it.
  • Line 2: c is [99 4] with cap 2, full. append copies to a new array, so c[0] = 0 no longer touches a.
  • Line 3: e and f both write slot 0 of d's array; the second append overwrites the first. Rule: always use the result of append as the only owner, or copy with slices.Clone.

8. Defer order puzzle

Basics · medium, predict the output

Write down the six lines this program prints, in order.

Hints

  • Deferred calls run last in, first out, when the function returns.
  • Arguments of a deferred call are evaluated at the defer line; a closure reads variables when it runs.
  • return n + 1 assigns to the named result before deferred functions run.
Solution
  • count: return sets n = 2, then the deferred closure makes it 20. This is how deferred code changes a returned error.
  • The closure prints 3 (the value at exit); "arg:" prints 1 (the value when deferred). Each loop iteration has its own i since Go 1.22, and the defers unwind 2, 1, 0.

Types and errors

Part 3 of 5 · exercises for go-types.html

Methods, interfaces, error values and generics, using the bank example. Exercise 13 is a puzzle and exercise 11 starts from a broken program.

9. Rupees with Stringer

Types and errors · easy

Define type Rupees int64 with a String() method that uses Indian digit grouping (last three digits, then groups of two): 150000 prints as ₹1,50,000. Print a few values, including a negative one, then print one value with %v and %d.

Hints

  • Format the absolute value with strconv.FormatInt, then insert commas from the right.
  • Inside String(), never pass r itself to fmt.Sprint: that calls String() again.
Solution
  • Any type with String() string satisfies fmt.Stringer; Println and %v call it, %d does not. It is Python's __str__.
  • int64(r) converts away the method, which is how you avoid infinite recursion.

10. Account with a sentinel error

Types and errors · easy

Build an Account with an owner, an unexported balance, and Deposit, Withdraw and Balance methods. Withdraw returns an error that wraps a package-level ErrInsufficientFunds and says who and how much; non-positive amounts return ErrInvalidAmount. Show that errors.Is finds the sentinel and == does not.

Hints

  • Sentinels are made once with errors.New at package level.
  • fmt.Errorf with the %w verb keeps the original error reachable.
  • Methods that change the balance need a pointer receiver.
Solution
  • Wrapping adds context ("who, how much") without losing the identity of the error. == fails because err is now a wrapper.
  • Keeping balance unexported means code outside the package can only change it through the methods, which enforce the rules.

11. Receiver bug hunt

Types and errors · medium, fix the program

This program should add 50 to every account and then 10 more to the first, but the balances never change. There are two separate bugs. Find both and fix them with the smallest change.

After your fix it must print:

Hints

  • Ask, for each call, which copy of the struct the method receives.
  • Fixing only the method prints [{Subhash Agrawani 110} {Hemkesh Agrawani 200}]: the loop still misses. Why?
Solution
  • A value receiver gets a copy; changes vanish when the method returns. Rule: if any method needs a pointer receiver, give all methods of that type pointer receivers.
  • The range variable is a copy of the element. Index into the slice, or store []*Account. accs[0].Deposit works because Go takes &accs[0] for you.

12. Notifier interface

Types and errors · medium

Define a Notifier interface with Notify(to, msg string) string and three implementations: Email (has a sender), SMS and Webhook (has a URL). Send one deposit alert through all three, then use a type switch to print which channels cost money (SMS only).

Hints

  • There is no implements keyword; having the method is enough.
  • var _ Notifier = Email{} makes the compiler check the interface for you.
  • A type switch is switch v := n.(type).
Solution
  • Interfaces are satisfied implicitly, so the consumer can define the small interface it needs. "Accept interfaces, return structs" is the usual interview line.
  • Reach for a type switch rarely: if every type needs different behaviour, that behaviour belongs in a method on the interface.

13. Nil interface puzzle

Types and errors · medium, predict the output

find(true) means "found, no error". Predict the four lines this prints.

Hints

  • An interface value holds two things: a type and a value.
  • It equals nil only when both are empty.
Solution
  • find returns an error whose type is *NotFound and whose value is a nil pointer. The type is set, so the interface is not nil, and every if err != nil check fires.
  • Fix: return the literal nil on success (if ok { return nil }), and never return a typed nil pointer as an interface.

14. Transfer errors

Types and errors · hard

Write transfer(from, to *Account, amt int) error. A frozen source account fails with the sentinel ErrFrozen; too little money fails with *InsufficientFundsError, a struct carrying the owner, the amount needed and the balance. transfer wraps either with context. The caller uses errors.As to read the shortfall and errors.Is for the frozen case.

Hints

  • Give the custom type a pointer receiver for Error() and return &InsufficientFundsError{...}.
  • errors.As needs a pointer to a variable of the target type: var e *InsufficientFundsError; errors.As(err, &e).
  • Only move money after every check passes.
Solution
  • Sentinel when the caller only needs "which kind"; a custom type when it needs data from the error. Both survive wrapping.
  • errors.As walks the chain and fills short. Passing short instead of &short panics at run time, and go vet catches it.

15. Map, Filter, Reduce

Types and errors · hard

Write generic Map, Filter and Reduce over slices, plus Sum constrained to number types, so that it also accepts a named type such as Rupees. From the amounts 500 12000 300 75000 2500, keep those of at least 1000, label them, and total them.

Hints

  • Map needs two type parameters: input and output element types.
  • A constraint is an interface listing types: interface{ ~int | ~float64 }. The ~ admits named types built on them.
Solution
  • Type arguments are inferred from the call, so Filter(amounts, ...) needs no [Rupees].
  • Without ~int in the constraint, Sum([]Rupees{...}) would not compile. In real code prefer a plain loop or slices functions; Go style does not chain functional helpers.

Concurrency

Part 4 of 5 · exercises for go-concurrency.html

Run every solution here with go run -race . as well. A program that prints the right answer can still have a race.

16. Parallel sum of squares

Concurrency · easy

Compute the sum of squares of 1 to 1000 using 4 goroutines, each handling one contiguous chunk, and combine the partial sums after all of them finish. Print each partial and the total.

Hints

  • Give each goroutine its own slot in a results slice; then no lock is needed.
  • wg.Go(f) (Go 1.25+) does Add(1), go and Done() in one call.
Solution
  • Different elements of a slice are different memory, so goroutines writing partial[w] do not race. Reading them is safe after wg.Wait().
  • The closure uses w directly: since Go 1.22 each iteration has its own variable. Before that you passed it as an argument.

17. Fix the data race

Concurrency · easy, fix the program

This counter should reach 1000 but prints a different number below it on most runs. Run it with -race, then fix it twice: once with sync.Mutex and once with sync/atomic.

The fixed program must print, every time:

Hints

  • count++ is three steps: read, add, write. Two goroutines can read the same old value.
  • atomic.Int64 has Add and Load methods and needs no initialisation.
Solution
  • Use atomic for a single counter or flag; use a mutex as soon as two values must change together (a balance and a history, say).
  • The race detector only reports races that actually happen during the run, so run your tests with -race in CI, not just once by hand.

18. Pipeline

Concurrency · medium

Build three stages connected by channels: generate(n) sends 1 to n, square(in) sends each value squared, and main sums what comes out. Each stage runs in its own goroutine and closes its output when done. Print the sum for n = 10 and n = 100.

Hints

  • Each stage function creates its channel, starts a goroutine, and returns the channel as receive-only (<-chan int).
  • The sender closes, never the receiver. for v := range ch stops when the channel is closed.
Solution
  • Directional channel types (<-chan) make the compiler reject a stage that tries to send on its input.
  • If main stopped reading early, both goroutines would block forever. Real pipelines pass a context so stages can stop (see exercises 20 and 21).

19. Ordered worker pool

Concurrency · medium

Process the words go rust python c java zig with 3 workers. Each job takes a different time (sleep 10 ms per letter) and returns the word in upper case with its length. Print the results in the input order, even though they finish in a different order.

Hints

  • Send the index along with each job, and return it with the result.
  • Close the jobs channel after sending everything; close the results channel after all workers finish.
  • With the indexes, place each result into a pre-sized slice.
Solution
  • The "wait then close results" goroutine is the standard fan-in ending. Calling wg.Wait() in main before reading would deadlock, since workers block on the unbuffered results channel.
  • Total time is about the longest worker's share, not the sum. An alternative is errgroup with SetLimit, from golang.org/x/sync.

20. Timeout and cancel

Concurrency · medium

Part A: fetchBalance(ctx) takes 100 ms. Call it with a 50 ms and a 300 ms timeout and print the result or the error. Part B: start 3 workers that tick every 10 ms until their context is cancelled; cancel after 35 ms, wait for all of them, and print which stopped (sorted, since stop order varies).

Hints

  • select on ctx.Done() and on the work, whichever is ready first wins.
  • context.WithTimeout returns a cancel function: always defer cancel().
  • Make the result channel buffered (size 1) so the slow goroutine can still send after nobody listens.
Solution
  • Timeouts are just cancellation with a deadline; both show up as ctx.Done(). ctx.Err() says which: context.DeadlineExceeded or context.Canceled.
  • Cancelling does not stop a goroutine; it only closes a channel. Each goroutine has to check ctx.Done() and return.

21. Spot the goroutine leak

Concurrency · hard, fix the program

first asks three replicas for a balance and returns the fastest answer. The answer is right, but after it returns, goroutines are left behind. Explain why, and fix it with a one-line change.

After the fix:

Hints

  • On an unbuffered channel a send waits until someone receives. How many receives does first do?
  • A goroutine blocked forever is never garbage collected.
Solution
  • One receive, three senders: the two slower goroutines block on ch <- forever. In a server that calls first per request, memory grows until the process dies.
  • A buffer the size of the number of senders lets every send complete. The other fix is a select with ctx.Done() around the send, which also lets the replicas stop working early.

22. Concurrent bank transfers

Concurrency · hard

Five accounts, one per family member, start with ₹1,000 each. Eight goroutines each make 1,000 random transfers of ₹1 to ₹100 between random accounts, skipping a transfer when the source is short. Lock per account (not one global lock) without deadlocking, and check the invariant: the total is still ₹5,000 and no balance is negative.

Hints

  • Goroutine 1 locks A then B while goroutine 2 locks B then A: that is a deadlock. Always lock in the same global order, for example by account id.
  • Transferring from an account to itself would lock the same mutex twice.
  • math/rand/v2 functions are safe to call from many goroutines.
Solution
  • Lock ordering is the classic deadlock answer. The check and the update happen under the same locks, so no other transfer can slip in between (no check-then-act race).
  • The individual balances differ on every run; the invariant does not. Testing invariants is how you test concurrent code with random input.

Mini projects

Part 5 of 5 · several concepts at once

Longer programs that combine the earlier parts. Give yourself 30 to 60 minutes for each before reading the solution.

23. Bank ledger with tests

Mini projects · project

Write a Ledger that records deposits and transfers on top of a Store interface (get and set a balance), with an in-memory store as the only implementation. Transfers reject unknown accounts, non-positive amounts and overdrafts with sentinel errors, and the ledger keeps a history. Put it in ledger.go, add a table-driven test for Transfer in ledger_test.go, and write a short main.go demo.

Hints

  • Depend on the interface inside Ledger, so a database store can replace the map later without touching the ledger code.
  • A table test is a slice of structs (name, inputs, want error) and a loop calling t.Run(tc.name, ...).
  • Build a fresh ledger inside each subtest so the cases do not affect each other.
Solution
  • MemStore is a named map type with methods; maps are references, so value receivers can still change it.
  • errors.Is(nil, nil) is true, which lets the "ok" row share the same check as the error rows.
  • This ledger is not safe for concurrent use. Adding a sync.Mutex to Ledger and locking in each method is the next step (exercise 22 shows why).

24. LRU cache

Mini projects · project

Build an LRU cache with a fixed capacity and O(1) Get and Put. When full, Put evicts the least recently used key; Get marks a key as recently used. With capacity 2: put a and b, get a, put c (evicts b), get b, put a again with a new value, and print the keys from most to least recent.

Hints

  • A doubly linked list keeps the order; a map from key to list element gives O(1) lookup.
  • container/list has PushFront, MoveToFront, Back and Remove.
  • Store the key inside the list element too, so eviction can delete it from the map.
Solution
  • list.Element.Value is any, hence the type assertions. A generic LRU[K comparable, V any] with your own node type removes them and is a good follow-up.
  • Both maps and lists are not safe for concurrent use; a shared cache needs a mutex around every method, including Get (it moves elements).

25. JSON API for accounts

Mini projects · project

Write an HTTP handler with three routes: POST /accounts creates an account from {"owner": ...}, POST /accounts/{id}/deposit adds {"amount": ...}, and GET /accounts/{id} returns the account as JSON. Return 201, 200, 400 or 404 as fitting. Drive it from main with httptest.NewRecorder, so it runs and exits without opening a port.

Hints

  • Since Go 1.22, http.ServeMux patterns take a method and wildcards: "GET /accounts/{id}", read with r.PathValue("id").
  • Handlers run concurrently in a real server, so guard the map with a mutex.
  • Struct tags like `json:"owner"` set the JSON field names.
Solution
  • httptest.NewRecorder plus ServeHTTP is also how you unit-test handlers: no network, no port, fast.
  • To serve it for real, replace the loop with http.ListenAndServe(":8080", api). JSON decoding matches field names case-insensitively, which is why Owner accepts "owner".

Where to go next

Mini projects

With these 25 done, the language itself is covered; what is left is the standard library. Read the package docs for net/http (servers, clients, middleware as handler wrappers), encoding/json (struct tags, streaming with Decoder, custom MarshalJSON) and database/sql (connection pools, QueryContext, transactions). Exercises 23 and 25 together are a good place to start: put the ledger behind the API and add a SQL store that satisfies the same Store interface.

Back to all Go pages.