Thuta Learning
Go
ExercisesProgrammingBeginner

Exercises: Core Basics Review

GoLesson 3135 min

What you'll walk away with

  • Read a function signature and list the edge cases (empty, nil, ties) before writing code
  • Range over a string to count runes (characters), not bytes
  • Build a result slice with append from a nil slice, and explain why index assignment panics
  • Return (value, bool) in the comma-ok style when there may be no result

Explain it simply

Explain it simply

This lesson teaches nothing new. It is where you write, by hand, what you read in the slices, maps, loops and functions lessons. Reading a recipe book does not make you a cook, and reading code does not put it in your fingers.

The plan: first read four solved exercises and notice why each line is written that way and which edge case it protects against. Then try the four new exercises in the mini challenge and run your attempt at least once before opening the solution.

Problem → Why → Solution

The problem: it compiles, then panics

Most people's first attempt at filterEven looks like this. They declare a result slice and store each even number at the same index it had in the input. It compiles. The moment it runs, the program stops with "panic: runtime error: index out of range [1] with length 0".

The message already holds the answer: evens has length 0. You cannot write to index 1 of a slice that has no elements yet.

attempt.go
func filterEven(nums []int) []int {
	var evens []int
	for i, n := range nums {
		if n%2 == 0 {
			evens[i] = n // panic: index out of range [1] with length 0
		}
	}
	return evens
}

Index assignment versus append

evens[i] = n can only overwrite an element that already exists; it never grows the slice. A nil slice has no elements, so every index is out of range. append(evens, n) adds a new element at the end and allocates a new array when needed. Reusing the input index would also leave gaps of 0 in the result.

The four ideas these exercises need

Before starting an exercise, read its signature and decide what it should return for empty input. Once the edge cases are settled, the code tends to become simple on its own.

1. Start from the zero value

sum starts with total := 0 and adds in a range loop. Ranging over a nil slice runs zero times, so sum(nil) returns 0. Maps work the same way: reading a missing key gives the zero value (0 for int), so counts[r]++ needs no existence check.

2. A string is bytes; range yields runes

A Go string holds UTF-8 bytes. len("မြန်မာ") is 18, yet it has only 6 characters (runes). for _, r := range s decodes UTF-8 and yields one rune at a time, which is why countChars uses it; indexing with s[i] gives single bytes.

3. Build result slices with append

var evens []int is a nil slice, and append grows it as needed. With no even numbers the function returns nil, which fmt prints as []. Its length is 0, so for most callers it behaves exactly like an empty slice.

4. Return a bool when there may be no answer

oldest(nil) has no oldest person. Returning Person{} could be mistaken for a nameless person aged 0, so the function returns (Person, bool). The loop starts from people[0] and replaces it only on a strictly greater age, so on a tie the first person wins.

ExerciseEdge caseWhat this solution returns
sumnil slice0
countCharsMyanmar textOne count per rune
filterEvenNo even numbersnil, printed as []
oldestNobody / a tiefalse / the first person
Mental model: signature, edge cases, code, check
  1. Read the signature
  2. Decide empty, nil and tie cases
  3. Loop from the zero value
  4. Predict the output, then run

Write the expected output down before you run. Wherever your prediction differs is where the most learning happens.

General pattern

go
func filter[T any](items []T, keep func(T) bool) []T {
	var out []T // nil is fine: append grows it
	for _, item := range items {
		if keep(item) {
			out = append(out, item)
		}
	}
	return out
}

The shape for building a new slice from the elements that pass a check: start from a nil slice and only ever add with append. filterEven is this pattern with keep replaced by n%2 == 0.

Four solved exercises

Each exercise is tried with a normal input and an edge case. countChars's result is not printed as a raw map: its keys are sorted and shown with %q, so runes appear as characters like 'g' instead of numbers like 103. The Myanmar word "မြန်မာ" shows the difference between bytes and runes.

main.go
package main

import (
	"fmt"
	"slices"
	"unicode/utf8"
)

// Exercise 1: add up a slice
func sum(nums []int) int {
	total := 0
	for _, n := range nums {
		total += n
	}
	return total
}

// Exercise 2: count characters (runes, not bytes)
func countChars(s string) map[rune]int {
	counts := make(map[rune]int)
	for _, r := range s {
		counts[r]++
	}
	return counts
}

// Exercise 3: keep only even numbers
func filterEven(nums []int) []int {
	var evens []int
	for _, n := range nums {
		if n%2 == 0 {
			evens = append(evens, n)
		}
	}
	return evens
}

// Exercise 4: find the oldest person
type Person struct {
	Name string
	Age  int
}

func oldest(people []Person) (Person, bool) {
	if len(people) == 0 {
		return Person{}, false
	}
	best := people[0]
	for _, p := range people[1:] {
		if p.Age > best.Age {
			best = p
		}
	}
	return best, true
}

func main() {
	fmt.Println("sum:", sum([]int{1, 2, 3, 4, 5}), "| empty:", sum(nil))

	counts := countChars("gopher go")
	keys := make([]rune, 0, len(counts))
	for r := range counts {
		keys = append(keys, r)
	}
	slices.Sort(keys)
	for _, r := range keys {
		fmt.Printf("%q:%d ", r, counts[r])
	}
	fmt.Println()

	word := "မြန်မာ"
	fmt.Println(len(word), "bytes,", utf8.RuneCountInString(word), "runes,",
		"'မ' x", countChars(word)['မ'])

	fmt.Println("evens:", filterEven([]int{1, 2, 3, 4, 5, 6}))
	none := filterEven([]int{1, 3})
	fmt.Println("no evens:", none, len(none), none == nil)

	people := []Person{{"Aye", 25}, {"Bo", 30}, {"Cho", 30}}
	if p, ok := oldest(people); ok {
		fmt.Println("oldest:", p)
	}
	_, ok := oldest(nil)
	fmt.Println("oldest of nobody found?", ok)
}

Code breakdown

  1. Count runesfor _, r := range s {

    Ranging over a string makes r a rune (a character). "မြန်မာ" is 18 bytes, but this loop runs only 6 times.

  2. Missing key is zerocounts[r]++

    For a key that is not there yet, counts[r] reads as 0, so ++ makes it 1. No "does it exist?" check is needed.

  3. Grow with appendevens = append(evens, n)

    Adding only with append avoids the index-out-of-range panic. When nothing is even, evens stays nil, which the output shows as [] 0 true.

  4. No answer, say sofunc oldest(people []Person) (Person, bool) {

    In the comma-ok style, an empty list gives false. The caller checks with if p, ok := oldest(people); ok { ... }.

  5. Ties keep the firstif p.Age > best.Age {

    Because of >, Bo and Cho both aged 30 leave Bo, the first one, in place. With >= the answer would become Cho, the last one.

You should see
sum: 15 | empty: 0
' ':1 'e':1 'g':2 'h':1 'o':2 'p':1 'r':1
18 bytes, 6 runes, 'မ' x 2
evens: [2 4 6]
no evens: [] 0 true
oldest: {Bo 30}
oldest of nobody found? false

Turn the edge cases into a table-driven test

Checking with Println in main is fine while learning, but you still verify by eye. Go code commonly uses table-driven tests instead: inputs and expected outputs listed in a slice of structs and checked in one loop. Every time you discover a new edge case, you add one line to the table.

Save the file below as filter_test.go next to main.go and run go test. slices.Equal treats a nil slice and an empty slice as equal, so the "no evens" case passes whichever one the function returns.

filter_test.go
package main

import (
	"slices"
	"testing"
)

func TestFilterEven(t *testing.T) {
	tests := []struct {
		name string
		in   []int
		want []int
	}{
		{"mixed", []int{1, 2, 3, 4}, []int{2, 4}},
		{"no evens", []int{1, 3}, nil},
		{"nil input", nil, nil},
	}
	for _, tc := range tests {
		if got := filterEven(tc.in); !slices.Equal(got, tc.want) {
			t.Errorf("%s: got %v, want %v", tc.name, got, tc.want)
		}
	}
}

In real projects

In real projects

These exercises show up in real code almost daily. Totalling an order list is the sum pattern, counting error types in a log is map counting, picking only active users is filtering, and finding the most recent login is the oldest pattern.

User input often contains multi-byte characters such as Myanmar, Thai or emoji, so checking a username's length with len is a common bug. For a rule like "at most 20 characters", use utf8.RuneCountInString. Returning (value, bool) or (value, error) from any lookup that may find nothing is also a pattern you will see all over the standard library. Reading from a map with v, ok := m[key] is itself one of the best-known examples of it.

Common mistakes

Common mistakes

Looping over a string byte by byte

for i := 0; i < len(s); i++ { counts[rune(s[i])]++ } looks right on English text, but on "မြန်မာ" it runs 18 times and counts byte values that are not characters at all. To count characters, use for _, r := range s.

Writing to a nil slice by index

evens[i] = n panics on a slice of length 0. Pre-sizing with make([]int, len(nums)) avoids the panic but leaves 0s where the odd numbers were. When filtering, use append.

Relying on map iteration order

for k, v := range counts can visit keys in a different order on every run; Go randomizes it on purpose. fmt.Println(counts) sorts the keys before printing, so that output is stable. If your own loop needs a fixed order, collect the keys into a slice and sort them with slices.Sort first.

Best practices

How to practise well

  • Run your own attempt and read the whole error message before opening the solution.
  • After each exercise, add one more edge case yourself: nil input, a tie, or multi-byte text.
  • Get used to running gofmt and go vet now and reading what the tools tell you.

Mini challenge

Four new exercises

Write the four functions below yourself, deciding each edge case from the signature first. In topWord, make sure map iteration order can never change the answer.

  • reverse(nums) reverses the slice in place and returns nothing
  • dedupe(words) removes repeated words and keeps the order of first appearance
  • wordFreq(text) counts each word, ignoring upper and lower case
  • topWord(freq) returns the most frequent word; on a tie, the alphabetically first one
challenge.go
package main

import (
	"fmt"
	"strings"
)

func reverse(nums []int) {
	// TODO: swap from both ends towards the middle
}

func dedupe(words []string) []string {
	// TODO: remember seen words in a map[string]bool
}

func wordFreq(text string) map[string]int {
	// TODO: strings.ToLower, then strings.Fields
}

func topWord(freq map[string]int) (string, int) {
	// TODO: higher count wins; equal count -> smaller word wins
}

func main() {
	// TODO: reverse []int{1, 2, 3, 4, 5}
	// TODO: dedupe []string{"go", "rust", "go", "zig", "rust"}
	// TODO: wordFreq + topWord on "Go is fun and go is fast"
	fmt.Println(strings.Repeat("-", 10))
}

Expected: reversed: [5 4 3 2 1], dedupe: [go rust zig], freq: map[and:1 fast:1 fun:1 go:2 is:2], then top word: "go" (2 times). "go" and "is" both appear twice, but "go" comes first alphabetically.

Show hint

For reverse, move in from both ends with for i, j := 0, len(nums)-1; i < j; i, j = i+1, j-1 and swap. For topWord, one condition handles ties too: n > bestN || (n == bestN && w < best).

Show solution
challenge.go
package main

import (
	"fmt"
	"strings"
)

// reverse flips the slice in place: no new slice, no return value.
func reverse(nums []int) {
	for i, j := 0, len(nums)-1; i < j; i, j = i+1, j-1 {
		nums[i], nums[j] = nums[j], nums[i]
	}
}

// dedupe drops repeated words, keeping each word's first position.
func dedupe(words []string) []string {
	seen := make(map[string]bool)
	var out []string
	for _, w := range words {
		if !seen[w] {
			seen[w] = true
			out = append(out, w)
		}
	}
	return out
}

func wordFreq(text string) map[string]int {
	freq := make(map[string]int)
	for _, w := range strings.Fields(strings.ToLower(text)) {
		freq[w]++
	}
	return freq
}

// topWord: the highest count wins; on a tie the alphabetically smaller
// word wins, so the answer never depends on map iteration order.
func topWord(freq map[string]int) (string, int) {
	best, bestN := "", 0
	for w, n := range freq {
		if n > bestN || (n == bestN && w < best) {
			best, bestN = w, n
		}
	}
	return best, bestN
}

func main() {
	nums := []int{1, 2, 3, 4, 5}
	reverse(nums)
	fmt.Println("reversed:", nums)

	fmt.Println("dedupe:", dedupe([]string{"go", "rust", "go", "zig", "rust"}))

	freq := wordFreq("Go is fun and go is fast")
	fmt.Println("freq:", freq)
	w, n := topWord(freq)
	fmt.Printf("top word: %q (%d times)\n", w, n)
}

Quick quiz 1 / 3

What does fmt.Println(len("မြန်မာ"), utf8.RuneCountInString("မြန်မာ")) print?

Quick quiz 2 / 3

After none := filterEven([]int{1, 3}), what does fmt.Println(none, len(none), none == nil) print?

Quick quiz 3 / 3

You run for k := range counts { fmt.Print(k) } twice on counts := map[string]int{"a": 1, "b": 2, "c": 3}. What happens?

What to remember

  • Read the signature and settle the empty, nil and tie cases before coding
  • len counts bytes; ranging over a string yields runes
  • Build filtered result slices from nil using append only
  • A function that may find nothing returns (value, bool)
  • Never rely on map iteration order; sort the keys when order matters

A Tour of Go — Go

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Exercises: Core Basics Review | Thuta Learning