Go Exercises
Time to practise! Each exercise gives you a starter program that already compiles and runs but doesn't do the job yet. Edit the code in the playground, press ▶ Run, and compare your output with the expected result. Try on your own first — then open the solution to compare.
| # | Exercise | Topics |
|---|---|---|
| 1 | Temperature table | loops, floats, Printf |
| 2 | FizzBuzz | for, switch, % |
| 3 | Reverse a string | runes, slices |
| 4 | Word counter | maps, sorting keys |
| 5 | Filter with generics | generics, functions as values |
| 6 | Bank account | structs, pointer methods, errors |
| 7 | Shapes | interfaces |
| 8 | Concurrent sum | goroutines, WaitGroup |
| 9 | Parse a config line | strings, strconv, errors |
1. Temperature table
Print Celsius values from 0 to 100 in steps of 25, with the Fahrenheit value (F = C × 9 / 5 + 32) to one decimal.
package main
import "fmt"
func main() {
for c := 0; c <= 100; c += 25 {
// TODO: compute f and print " 0°C = 32.0°F"
fmt.Println(c)
}
}0
25
50
75
100
Expected: 0°C = 32.0°F, 25°C = 77.0°F, … up to 100°C = 212.0°F.
Show solution
package main
import "fmt"
func main() {
for c := 0; c <= 100; c += 25 {
f := float64(c)*9/5 + 32
fmt.Printf("%3d°C = %5.1f°F\n", c, f)
}
}Output:
0°C = 32.0°F
25°C = 77.0°F
50°C = 122.0°F
75°C = 167.0°F
100°C = 212.0°F2. FizzBuzz
For the numbers 1 to 15, print Fizz for multiples of 3, Buzz for multiples of 5, FizzBuzz for multiples of both, and the number otherwise. Use a tagless switch.
package main
import "fmt"
func main() {
for n := 1; n <= 15; n++ {
// TODO: use switch { case ... } to choose what to print
fmt.Print(n, " ")
}
fmt.Println()
}1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Show solution
package main
import "fmt"
func main() {
for n := 1; n <= 15; n++ {
switch {
case n%15 == 0:
fmt.Print("FizzBuzz ")
case n%3 == 0:
fmt.Print("Fizz ")
case n%5 == 0:
fmt.Print("Buzz ")
default:
fmt.Print(n, " ")
}
}
fmt.Println()
}Output:
1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzzThe n%15 case must come first — a switch runs only the first matching case.
3. Reverse a string
Write reverse(s string) string that works with any Unicode text, including "héllo, 世界". Reversing bytes would corrupt multi-byte characters, so work with runes.
package main
import "fmt"
func reverse(s string) string {
// TODO: convert to []rune, swap from both ends, convert back
return s
}
func main() {
fmt.Println(reverse("gopher"))
fmt.Println(reverse("héllo, 世界"))
}gopher
héllo, 世界
Show solution
package main
import "fmt"
func reverse(s string) string {
r := []rune(s)
for i, j := 0, len(r)-1; i < j; i, j = i+1, j-1 {
r[i], r[j] = r[j], r[i]
}
return string(r)
}
func main() {
fmt.Println(reverse("gopher"))
fmt.Println(reverse("héllo, 世界"))
}Output:
rehpog
界世 ,olléh4. Word counter
Count how often each word appears (ignoring case and the punctuation .,!) and print the words alphabetically with their counts.
package main
import (
"fmt"
"strings"
)
func main() {
text := "Go is fun. Go is fast! Is Go simple, or is Go easy?"
words := strings.Fields(strings.ToLower(text))
// TODO: trim punctuation, count in a map, print sorted
fmt.Println(len(words), "words")
}13 words
Show solution
package main
import (
"fmt"
"maps"
"slices"
"strings"
)
func main() {
text := "Go is fun. Go is fast! Is Go simple, or is Go easy?"
counts := map[string]int{}
for _, w := range strings.Fields(strings.ToLower(text)) {
w = strings.Trim(w, ".,!?")
counts[w]++
}
for _, w := range slices.Sorted(maps.Keys(counts)) {
fmt.Printf("%-6s %d\n", w, counts[w])
}
}Output:
easy 1
fast 1
fun 1
go 4
is 4
or 1
simple 15. Filter with generics
Write a generic Filter[T any](items []T, keep func(T) bool) []T and use it for both numbers and strings.
package main
import "fmt"
// TODO: write Filter here
func main() {
nums := []int{4, 7, 10, 13, 16}
names := []string{"Ada", "Bob", "Alan", "Cy"}
fmt.Println(nums, names)
}[4 7 10 13 16] [Ada Bob Alan Cy]
Expected after your change: [4 10 16] (even numbers) and [Ada Alan] (names starting with "A").
Show solution
package main
import (
"fmt"
"strings"
)
func Filter[T any](items []T, keep func(T) bool) []T {
var out []T
for _, it := range items {
if keep(it) {
out = append(out, it)
}
}
return out
}
func main() {
nums := []int{4, 7, 10, 13, 16}
names := []string{"Ada", "Bob", "Alan", "Cy"}
evens := Filter(nums, func(n int) bool { return n%2 == 0 })
aNames := Filter(names, func(s string) bool { return strings.HasPrefix(s, "A") })
fmt.Println(evens, aNames)
}Output:
[4 10 16] [Ada Alan]6. Bank account
Complete the Withdraw method: it must return an error (and leave the balance unchanged) if the amount is not positive or larger than the balance.
package main
import (
"fmt"
)
type Account struct {
Owner string
Balance int
}
func (a *Account) Deposit(amount int) {
a.Balance += amount
}
func (a *Account) Withdraw(amount int) error {
// TODO: validate and return an error when needed
a.Balance -= amount
return nil
}
func main() {
acc := &Account{Owner: "Kim"}
acc.Deposit(100)
for _, amt := range []int{30, 200, -5, 70} {
err := acc.Withdraw(amt)
fmt.Printf("withdraw %d: err=%v balance=%d\n", amt, err, acc.Balance)
}
}withdraw 30: err=<nil> balance=70
withdraw 200: err=<nil> balance=-130
withdraw -5: err=<nil> balance=-125
withdraw 70: err=<nil> balance=-195
Show solution
package main
import (
"errors"
"fmt"
)
type Account struct {
Owner string
Balance int
}
func (a *Account) Deposit(amount int) {
a.Balance += amount
}
func (a *Account) Withdraw(amount int) error {
if amount <= 0 {
return errors.New("amount must be positive")
}
if amount > a.Balance {
return fmt.Errorf("insufficient funds: balance %d", a.Balance)
}
a.Balance -= amount
return nil
}
func main() {
acc := &Account{Owner: "Kim"}
acc.Deposit(100)
for _, amt := range []int{30, 200, -5, 70} {
err := acc.Withdraw(amt)
fmt.Printf("withdraw %d: err=%v balance=%d\n", amt, err, acc.Balance)
}
}Output:
withdraw 30: err=<nil> balance=70
withdraw 200: err=insufficient funds: balance 70 balance=70
withdraw -5: err=amount must be positive balance=70
withdraw 70: err=<nil> balance=07. Shapes
Add a Square type with a Side field so that it satisfies the Shape interface, then add a Square{Side: 3} to the list. Print the total area.
package main
import "fmt"
type Shape interface {
Area() float64
Name() string
}
type Rect struct{ W, H float64 }
func (r Rect) Area() float64 { return r.W * r.H }
func (r Rect) Name() string { return "rect" }
// TODO: add Square here
func main() {
shapes := []Shape{Rect{2, 5}}
total := 0.0
for _, s := range shapes {
fmt.Printf("%s: %.1f\n", s.Name(), s.Area())
total += s.Area()
}
fmt.Printf("total: %.1f\n", total)
}rect: 10.0
total: 10.0
Show solution
package main
import "fmt"
type Shape interface {
Area() float64
Name() string
}
type Rect struct{ W, H float64 }
func (r Rect) Area() float64 { return r.W * r.H }
func (r Rect) Name() string { return "rect" }
type Square struct{ Side float64 }
func (s Square) Area() float64 { return s.Side * s.Side }
func (s Square) Name() string { return "square" }
func main() {
shapes := []Shape{Rect{2, 5}, Square{Side: 3}}
total := 0.0
for _, s := range shapes {
fmt.Printf("%s: %.1f\n", s.Name(), s.Area())
total += s.Area()
}
fmt.Printf("total: %.1f\n", total)
}Output:
rect: 10.0
square: 9.0
total: 19.08. Concurrent sum
Split the slice into 4 parts, sum each part in its own goroutine, and add the partial sums. Each goroutine should write to its own slot in partial.
package main
import "fmt"
func main() {
nums := make([]int, 1000)
for i := range nums {
nums[i] = i + 1
}
const parts = 4
partial := make([]int, parts)
// TODO: start one goroutine per part and wait for all of them
total := 0
for _, p := range partial {
total += p
}
fmt.Println(partial, total)
}[0 0 0 0] 0
Show solution
package main
import (
"fmt"
"sync"
)
func main() {
nums := make([]int, 1000)
for i := range nums {
nums[i] = i + 1
}
const parts = 4
partial := make([]int, parts)
size := len(nums) / parts
var wg sync.WaitGroup
for p := range parts {
wg.Go(func() {
for _, n := range nums[p*size : (p+1)*size] {
partial[p] += n
}
})
}
wg.Wait()
total := 0
for _, p := range partial {
total += p
}
fmt.Println(partial, total)
}Output:
[31375 93875 156375 218875] 5005009. Parse a config line
Write parseLine(line string) (string, int, error) that turns "timeout = 30" into the key "timeout" and the number 30. Return an error if there is no = or the value is not a number.
package main
import (
"fmt"
)
func parseLine(line string) (string, int, error) {
// TODO: use strings.Cut, strings.TrimSpace and strconv.Atoi
return "", 0, nil
}
func main() {
for _, line := range []string{"timeout = 30", "retries=5", "debug", "port = eighty"} {
key, val, err := parseLine(line)
fmt.Printf("%q -> key=%q val=%d err=%v\n", line, key, val, err)
}
}"timeout = 30" -> key="" val=0 err=<nil>
"retries=5" -> key="" val=0 err=<nil>
"debug" -> key="" val=0 err=<nil>
"port = eighty" -> key="" val=0 err=<nil>
Show solution
package main
import (
"fmt"
"strconv"
"strings"
)
func parseLine(line string) (string, int, error) {
k, v, ok := strings.Cut(line, "=")
if !ok {
return "", 0, fmt.Errorf("missing '=' in %q", line)
}
key := strings.TrimSpace(k)
n, err := strconv.Atoi(strings.TrimSpace(v))
if err != nil {
return key, 0, fmt.Errorf("value of %s: %w", key, err)
}
return key, n, nil
}
func main() {
for _, line := range []string{"timeout = 30", "retries=5", "debug", "port = eighty"} {
key, val, err := parseLine(line)
fmt.Printf("%q -> key=%q val=%d err=%v\n", line, key, val, err)
}
}Output:
"timeout = 30" -> key="timeout" val=30 err=<nil>
"retries=5" -> key="retries" val=5 err=<nil>
"debug" -> key="" val=0 err=missing '=' in "debug"
"port = eighty" -> key="port" val=0 err=value of port: strconv.Atoi: parsing "eighty": invalid syntaxTest yourself
Why does reversing a string byte by byte break "世界"?
- Strings are immutable
- Each of these characters is several bytes; reversing bytes scrambles the UTF-8 encoding
- Go cannot print Chinese
- It works fine
In FizzBuzz with a tagless switch, why must the n%15 == 0 case come first?
- Style only
- Only the first matching case runs, so
n%3would catch 15 first %15is slower- Switch cases are evaluated bottom-up