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
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
diffworks 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
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.
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
switchwith no expression after it tests eachcaseas a boolean. - Cases are checked top to bottom and the first true one wins.
strconv.Itoaturns an int into its decimal string.
Solution
- The
n%15case must come first. Go cases do not fall through, so there is nobreakto forget. make([]string, 0, 15)sets the capacity up front, soappendnever 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
[]runefirst, then swap from both ends. - Look at
unicode/utf8for counting.
Solution
len(s)counts bytes:éis 2 bytes and each Chinese character is 3. Python'slencounts code points, so this surprises Python developers.slices.Reverse(r)does the swap loop for you. Neither handles combining marks (anefollowed 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 whymap[T]struct{}is the idiomatic set.map[T]boolalso works and reads more easily.slices.Compactonly 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.Fieldssplits on any run of whitespace.- Map iteration order is random by design. Collect the keys and sort them.
slices.SortFunctakes 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'sCounterwithout the import.cmp.Orreturns 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
newIDGencreates a fresh variable.
Solution
- The closure keeps
nextalive afternewIDGenreturns; the compiler moves it to the heap. Python needsnonlocalfor the same thing. - It is not safe for concurrent use. Two goroutines calling
savings()race onnext; useatomic.Int64if 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
lenandcapofb,candd. appendwrites in place when there is spare capacity, and copies to a new array when there is not.
Solution
- Line 1:
bhas len 2, cap 4, soappendwrites 99 intoa[2]. Both see it. - Line 2:
cis[99 4]with cap 2, full.appendcopies to a new array, soc[0] = 0no longer touchesa. - Line 3:
eandfboth write slot 0 ofd's array; the second append overwrites the first. Rule: always use the result ofappendas the only owner, or copy withslices.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
deferline; a closure reads variables when it runs. return n + 1assigns to the named result before deferred functions run.
Solution
count:returnsetsn = 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 ownisince 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 passritself tofmt.Sprint: that callsString()again.
Solution
- Any type with
String() stringsatisfiesfmt.Stringer;Printlnand%vcall it,%ddoes 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.Newat package level. fmt.Errorfwith the%wverb 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 becauseerris now a wrapper. - Keeping
balanceunexported 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].Depositworks 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
implementskeyword; 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
nilonly when both are empty.
Solution
findreturns anerrorwhose type is*NotFoundand whose value is a nil pointer. The type is set, so the interface is not nil, and everyif err != nilcheck fires.- Fix: return the literal
nilon 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.Asneeds 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.Aswalks the chain and fillsshort. Passingshortinstead of&shortpanics at run time, andgo vetcatches 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
Mapneeds 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
~intin the constraint,Sum([]Rupees{...})would not compile. In real code prefer a plain loop orslicesfunctions; 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+) doesAdd(1),goandDone()in one call.
Solution
- Different elements of a slice are different memory, so goroutines writing
partial[w]do not race. Reading them is safe afterwg.Wait(). - The closure uses
wdirectly: 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.Int64hasAddandLoadmethods 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
-racein 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 chstops when the channel is closed.
Solution
- Directional channel types (
<-chan) make the compiler reject a stage that tries to send on its input. - If
mainstopped reading early, both goroutines would block forever. Real pipelines pass acontextso 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()inmainbefore 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
errgroupwithSetLimit, fromgolang.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
selectonctx.Done()and on the work, whichever is ready first wins.context.WithTimeoutreturns acancelfunction: alwaysdefer 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.DeadlineExceededorcontext.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
firstdo? - 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 callsfirstper 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
selectwithctx.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/v2functions 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
MemStoreis 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.MutextoLedgerand 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/listhasPushFront,MoveToFront,BackandRemove.- Store the key inside the list element too, so eviction can delete it from the map.
Solution
list.Element.Valueisany, hence the type assertions. A genericLRU[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.ServeMuxpatterns take a method and wildcards:"GET /accounts/{id}", read withr.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.NewRecorderplusServeHTTPis 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 whyOwneraccepts"owner".
Where to go next
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.