Skip to content
Tutorials Center
My learning

Topics

Lesson 143 of 147 ยท Practice and Review

Go Practice Exercises

30 graded Go exercises with solutions on loops, functions, strings, slices, maps, structs, interfaces, errors, generics and goroutines. Run Go in your browser.

You learn Go by writing Go. Lessons build understanding, but only practice builds the reflexes: reaching for strings.Fields instead of a hand-made splitter, checking the ok of a map read, returning an error instead of panicking, closing a channel from the sending side. This page collects 30 exercises that cover the whole course, grouped by topic and ordered from beginner to advanced.

Every exercise has a short task, an editor with starter code, and a hidden solution. The starter code compiles and runs as given: the functions you must write are stubs that return a placeholder value, and the comments in main show the output you should get once your code works. Replace the stub body, press Run, and compare.

  • Try first, peek later. Give each exercise a real attempt before you open the solution. A few minutes of being stuck is where the learning happens.
  • Compare, don't copy. Your solution can look different from ours and still be right. Read ours for ideas, then improve yours.
  • Read the compiler. Go reports the exact line and column of a mistake, such as declared and not used or missing return. Treat each message as a hint.
  • Test the edges. Empty slices, zero, negative numbers, missing map keys and non-English text are where Go programs break. Most exercises include an edge case in their test calls.

Each group links to the lessons it practices. Keep the cheat sheet open in another tab, and look at the 50 classic programs if you want worked examples first.

Basics and control flow

These practice variables, operators, if, switch, loops and reading input.

1. Times table (Beginner)

Read one whole number from the Input box and print its times table from 1 to 10 in the format shown in the comment. Use Printf with a field width so the columns line up.

Go Exercise 1: Times table

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Show solution
Go
for i := 1; i <= 10; i++ {
	fmt.Printf("%d x %2d = %2d\n", n, i, n*i)
}

%2d pads each number to two characters, so the = signs and the results line up. For tables whose products reach three digits, widen the last field to %3d.

2. Temperature table (Beginner)

Write celsiusToFahrenheit using the formula F = C * 9 / 5 + 32. The program prints a table from 0 to 100 degrees in steps of 20.

Go Exercise 2: Temperature table

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Show solution
Go
func celsiusToFahrenheit(c float64) float64 {
	return c*9/5 + 32
}

All operands are float64, so the division by 5 keeps its fraction. With integers, 9 / 5 would be 1 and every answer would be wrong. Go never converts between numeric types for you.

3. Classify a triangle (Beginner)

Write classify(a, b, c int) string that returns "invalid" (a side is zero or negative, or the two shorter sides do not add up to more than the longest), "equilateral" (three equal sides), "isosceles" (exactly two equal) or "scalene" (all different). A switch with no expression keeps the checks in order.

Go Exercise 3: Classify a triangle

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Show solution
Go
func classify(a, b, c int) string {
	switch {
	case a <= 0 || b <= 0 || c <= 0 || a+b <= c || a+c <= b || b+c <= a:
		return "invalid"
	case a == b && b == c:
		return "equilateral"
	case a == b || b == c || a == c:
		return "isosceles"
	}
	return "scalene"
}

The first case catches every invalid triangle, so later cases can assume valid sides. The order of the cases matters: an equilateral triangle also satisfies the "two equal" test, so it must be checked first.

4. Sum of multiples (Beginner)

Write sumMultiples(limit int) int that returns the sum of all numbers below limit that are multiples of 3 or 5.

Go Exercise 4: Sum of multiples

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Show solution
Go
func sumMultiples(limit int) int {
	sum := 0
	for n := 1; n < limit; n++ {
		if n%3 == 0 || n%5 == 0 {
			sum += n
		}
	}
	return sum
}

A number such as 15 is a multiple of both, but the || test adds it once, which is what the task asks for. Checking each number separately and summing them would count it twice.

5. Letter grades (Beginner)

Write grade(score int) string: 90 to 100 is "A", 80 to 89 "B", 70 to 79 "C", 60 to 69 "D", 0 to 59 "F", and anything outside 0 to 100 is "invalid". Use a switch with conditions.

Go Exercise 5: Letter grades

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Show solution
Go
func grade(score int) string {
	switch {
	case score < 0 || score > 100:
		return "invalid"
	case score >= 90:
		return "A"
	case score >= 80:
		return "B"
	case score >= 70:
		return "C"
	case score >= 60:
		return "D"
	default:
		return "F"
	}
}

Cases are tested from top to bottom and the first true one wins, so each >= test only needs the lower bound: by the time score >= 80 is reached, the score is already known to be below 90.

Functions and closures

These practice functions, multiple results, variadic functions, closures and higher-order functions.

6. Minimum and maximum (Beginner)

Write minMax(nums []int) (lo, hi int, ok bool). For an empty slice return ok == false, because there is no minimum of nothing.

Go Exercise 6: Minimum and maximum

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Show solution
Go
func minMax(nums []int) (lo, hi int, ok bool) {
	if len(nums) == 0 {
		return 0, 0, false
	}
	lo, hi = nums[0], nums[0]
	for _, n := range nums[1:] {
		lo = min(lo, n)
		hi = max(hi, n)
	}
	return lo, hi, true
}

The "comma ok" result is Go's way to say "there was no answer". Starting from the first element avoids guessing a starting minimum such as math.MaxInt. The min and max builtins exist since Go 1.21.

7. A variadic average (Beginner)

Write average(nums ...float64) float64. With no arguments it should return 0 instead of dividing by zero. The test also passes a slice with values....

Go Exercise 7: A variadic average

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Show solution
Go
func average(nums ...float64) float64 {
	if len(nums) == 0 {
		return 0
	}
	sum := 0.0
	for _, n := range nums {
		sum += n
	}
	return sum / float64(len(nums))
}

Inside the function nums is an ordinary []float64. Dividing a float by zero does not panic in Go (it gives NaN or +Inf), so the explicit check for an empty slice is what keeps the answer meaningful.

8. A counter with a step (Intermediate)

Write makeCounter(step int) func() int. Each call of the returned function adds step to a private total and returns it. Two counters must not share state.

Go Exercise 8: A counter with a step

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Show solution
Go
func makeCounter(step int) func() int {
	total := 0
	return func() int {
		total += step
		return total
	}
}

total lives as long as the returned function does, because the closure captured the variable itself. Each call of makeCounter creates a new total, which is why c and d count independently.

9. Compose functions (Intermediate)

Write compose(fs ...func(int) int) func(int) int that returns a function applying fs from left to right. With no functions it returns its argument unchanged.

Go Exercise 9: Compose functions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Show solution
Go
func compose(fs ...func(int) int) func(int) int {
	return func(x int) int {
		for _, f := range fs {
			x = f(x)
		}
		return x
	}
}

The returned closure captures the slice fs and loops over it on every call. Functions are values, so a slice of functions is as ordinary as a slice of numbers.

Strings and text

These practice strings, bytes and runes and the strings package.

10. Word statistics (Beginner)

Write wordStats(s string) (words int, longest string): the number of words (separated by any amount of whitespace) and the longest word. If two words are equally long, return the first one. For an empty text return 0 and "".

Go Exercise 10: Word statistics

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Show solution
Go
func wordStats(s string) (words int, longest string) {
	for _, w := range strings.Fields(s) {
		words++
		if len(w) > len(longest) {
			longest = w
		}
	}
	return words, longest
}

strings.Fields splits around runs of whitespace and ignores leading and trailing spaces, which is what Split(s, " ") gets wrong. Using > instead of >= keeps the first of equally long words.

The solution also imports strings.

11. Reverse the words (Beginner)

Write reverseWords(s string) string so that "go is fun" becomes "fun is go". Extra spaces between and around the words should disappear.

Go Exercise 11: Reverse the words

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Show solution
Go
func reverseWords(s string) string {
	words := strings.Fields(s)
	slices.Reverse(words)
	return strings.Join(words, " ")
}

Split with Fields, reverse the slice in place with slices.Reverse, join with one space. An empty string gives an empty slice, and Join of nothing is "".

The solution also imports slices and strings.

12. Mask an email address (Intermediate)

Write maskEmail(email string) string that keeps the first character of the name and the whole domain: "[email protected]" becomes "m***@example.com". Text without an @ is returned unchanged.

Go Exercise 12: Mask an email address

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Show solution
Go
func maskEmail(email string) string {
	name, domain, found := strings.Cut(email, "@")
	if !found || name == "" {
		return email
	}
	first, _ := utf8.DecodeRuneInString(name)
	return string(first) + "***@" + domain
}

strings.Cut splits at the first @ and reports whether it found one. Taking the first rune with utf8.DecodeRuneInString instead of name[:1] keeps names such as รฉlan intact: name[:1] would cut the two-byte รฉ in half.

The solution also imports strings and unicode/utf8.

13. Parse key=value pairs (Intermediate)

Write parsePairs(s string) map[string]string for text like "a=1;b=2;c;d=x=y". Pairs are separated by ;, and a key is separated from its value by the first =. Entries without an = are skipped. The test prints the keys in sorted order.

Go Exercise 13: Parse key=value pairs

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Show solution
Go
func parsePairs(s string) map[string]string {
	result := make(map[string]string)
	for _, part := range strings.Split(s, ";") {
		key, value, found := strings.Cut(part, "=")
		if found && key != "" {
			result[key] = value
		}
	}
	return result
}

Cut splits at the first separator only, so the value x=y survives. Returning a non-nil empty map is friendlier than nil, because callers can safely read from both (a nil map reads fine) and, unlike a nil map, write to the result.

The solution also imports strings.

Slices and maps

These practice slices, slice internals, maps and the slices and maps packages.

14. Keep the even numbers (Beginner)

Write filterEven(nums []int) []int that returns a new slice with the even numbers, in the original order. The input must not change.

Go Exercise 14: Keep the even numbers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Show solution
Go
func filterEven(nums []int) []int {
	var result []int
	for _, n := range nums {
		if n%2 == 0 {
			result = append(result, n)
		}
	}
	return result
}

append on a nil slice allocates as needed, so the result starts as var result []int. When nothing matches, the result stays nil, which prints as [] and works with len, range and append.

15. Reverse in place (Beginner)

Write reverse(s []int) that reverses the slice in place, without allocating a second slice. It has no return value, because the caller sees the change through the shared array.

Go Exercise 15: Reverse in place

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Show solution
Go
func reverse(s []int) {
	for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {
		s[i], s[j] = s[j], s[i]
	}
}

Two indexes walk towards each other and swap. A slice is a small header that points to the shared array, so changes through s are visible to the caller, even for a sub-slice such as c[1:4].

16. The most common word (Intermediate)

Write mostCommon(words []string) string. When two words appear equally often, return the one that comes first alphabetically. For no words return "".

Go Exercise 16: The most common word

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Show solution
Go
func mostCommon(words []string) string {
	counts := make(map[string]int)
	for _, w := range words {
		counts[w]++
	}
	best, bestCount := "", 0
	for w, c := range counts {
		if c > bestCount || (c == bestCount && w < best) {
			best, bestCount = w, c
		}
	}
	return best
}

Map iteration order is random, so without the tie-break (w < best) the answer could change from run to run. A deterministic rule makes the function testable.

17. Invert a map (Intermediate)

Write invert(m map[string]int) map[int][]string: for every value, the sorted list of keys that have it. Print the result with the keys in order.

Go Exercise 17: Invert a map

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Show solution
Go
func invert(m map[string]int) map[int][]string {
	result := make(map[int][]string)
	for key, value := range m {
		result[value] = append(result[value], key)
	}
	for _, keys := range result {
		slices.Sort(keys)
	}
	return result
}

Appending to result[value] works even for a missing key, because a missing key reads as a nil slice. The keys are collected in random order, so each list is sorted at the end.

18. Remove by index (Intermediate)

Write removeAt(s []int, i int) []int that removes the element at index i, keeps the order, and returns the shortened slice. An index out of range returns the slice unchanged.

Go Exercise 18: Remove by index

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Show solution
Go
func removeAt(s []int, i int) []int {
	if i < 0 || i >= len(s) {
		return s
	}
	return append(s[:i], s[i+1:]...)
}

append(s[:i], s[i+1:]...) shifts the tail one place left in the same array, which is why the last line shows a changed original. If the caller must keep the old contents, copy first (slices.Clone). The standard library has slices.Delete for this job; it also zeroes the freed slot.

19. Chunks (Advanced)

Write chunk(s []int, size int) [][]int that splits a slice into pieces of at most size elements. For size <= 0 return nil. The pieces may share memory with the input.

Go Exercise 19: Chunks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Show solution
Go
func chunk(s []int, size int) [][]int {
	if size <= 0 {
		return nil
	}
	var chunks [][]int
	for size < len(s) {
		chunks = append(chunks, s[:size:size])
		s = s[size:]
	}
	if len(s) > 0 {
		chunks = append(chunks, s)
	}
	return chunks
}

s[:size:size] is a full slice expression: it limits the capacity of each chunk, so an append to one chunk can never overwrite the start of the next. Reslicing s = s[size:] walks forward without copying anything.

Structs, methods and interfaces

These practice structs, methods, pointer receivers, embedding, interfaces and constructors.

20. A rectangle type (Beginner)

Give Rect the methods Area() and Perimeter() (value receivers) and Scale(factor float64), which multiplies both sides and therefore needs a pointer receiver.

Go Exercise 20: A rectangle type

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Show solution
Go
func (r Rect) Area() float64      { return r.W * r.H }
func (r Rect) Perimeter() float64 { return 2 * (r.W + r.H) }

func (r *Rect) Scale(factor float64) {
	r.W *= factor
	r.H *= factor
}

With a value receiver, Scale would change a copy and the caller would see nothing. Calling r.Scale(2) on an addressable variable works without writing (&r).Scale(2): Go takes the address for you.

21. A Stringer (Beginner)

Make Temp print like 21.5ยฐC by implementing the String() string method. The fmt package calls it automatically. Use one decimal digit.

Go Exercise 21: A Stringer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Show solution
Go
func (t Temp) String() string {
	return fmt.Sprintf("%.1fยฐC", float64(t))
}

Converting with float64(t) is essential: Sprintf("%.1f", t) would call t.String() again and recurse forever. 100.25 is exactly representable, and Go rounds an exact tie to the even digit, so %.1f shows 100.2.

22. A chorus of animals (Intermediate)

Implement Speak() string for Dog ("<name> says woof") and Cat ("<name> says meow") so both satisfy Animal. Then write chorus(animals []Animal) string that joins all the sentences with "; ".

Go Exercise 22: A chorus of animals

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Show solution
Go
func (d Dog) Speak() string { return d.Name + " says woof" }
func (c Cat) Speak() string { return c.Name + " says meow" }

func chorus(animals []Animal) string {
	parts := make([]string, 0, len(animals))
	for _, a := range animals {
		parts = append(parts, a.Speak())
	}
	return strings.Join(parts, "; ")
}

Nobody declares that Dog implements Animal: having the method is enough. The slice holds different concrete types behind one interface, and chorus neither knows nor cares which is which.

The solution also imports strings.

23. Embedding and overriding (Intermediate)

Employee embeds Person, so it already has Person's Greeting. Give Employee its own Greeting that returns the person's greeting followed by " and I work as <title>".

Go Exercise 23: Embedding and overriding

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Show solution
Go
func (e Employee) Greeting() string {
	return e.Person.Greeting() + " and I work as " + e.Title
}

The outer method shadows the promoted one, and the embedded value is still reachable as e.Person. This is composition, not inheritance: Person.Greeting still sees only a Person, never the Employee around it.

24. A safe account (Advanced)

Write NewAccount (returns an error when the owner is empty or the opening balance is negative), Withdraw (returns an error that wraps ErrInsufficientFunds when the balance is too low and leaves the balance unchanged) and Balance.

Go Exercise 24: A safe account

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Show solution
Go
func NewAccount(owner string, opening int) (*Account, error) {
	if owner == "" {
		return nil, errors.New("owner must not be empty")
	}
	if opening < 0 {
		return nil, fmt.Errorf("opening balance %d is negative", opening)
	}
	return &Account{owner: owner, balance: opening}, nil
}

func (a *Account) Withdraw(amount int) error {
	if amount > a.balance {
		return fmt.Errorf("withdraw %d from %s: %w", amount, a.owner, ErrInsufficientFunds)
	}
	a.balance -= amount
	return nil
}

func (a *Account) Balance() int { return a.balance }

A constructor can refuse to build an invalid value, and unexported fields stop other packages from bypassing the checks. The %w verb keeps the original error inside the new message, so callers can still test it with errors.Is.

Errors

These practice errors as values, wrapping, custom errors and panic and recover.

25. A custom error type (Advanced)

Give ValidationError an Error() method that returns "<Field>: <Reason>". Write validateAge(age int) error (valid ages are 0 to 150, otherwise a *ValidationError for the field "age") and fieldOf(err error) string, which uses errors.As to return the failing field of any error in the chain, or "".

Go Exercise 25: A custom error type

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Show solution
Go
func (e *ValidationError) Error() string {
	return e.Field + ": " + e.Reason
}

func validateAge(age int) error {
	if age < 0 || age > 150 {
		return &ValidationError{Field: "age", Reason: "must be between 0 and 150"}
	}
	return nil
}

func fieldOf(err error) string {
	var ve *ValidationError
	if errors.As(err, &ve) {
		return ve.Field
	}
	return ""
}

errors.As walks the chain of wrapped errors and stores the first *ValidationError it finds into ve. Because validateAge returns the plain nil for valid input (not a typed nil pointer), err != nil checks keep working. Returning a nil *ValidationError inside an error would be non-nil, a classic Go trap.

26. Turn a panic into an error (Advanced)

Write safeDivide(a, b int) (result int, err error). Integer division by zero panics at run time. Use defer and recover so the function returns an error instead of crashing.

Go Exercise 26: Turn a panic into an error

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Show solution
Go
func safeDivide(a, b int) (result int, err error) {
	defer func() {
		if r := recover(); r != nil {
			err = fmt.Errorf("recovered: %v", r)
		}
	}()
	return a / b, nil
}

recover only works inside a deferred function. The error is assigned to the named result err, because a deferred closure can change named results after the panic has started. In real code, check b == 0 first and return an error; recover is for boundaries such as a server that must survive a bug in one handler.

Generics

These practice type parameters, constraints and generic types.

27. Contains and MaxOf (Intermediate)

Write the generic functions Contains[T comparable](s []T, v T) bool and MaxOf[T cmp.Ordered](a, b T) T. They must work for ints, strings and floats alike.

Go Exercise 27: Contains and MaxOf

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Show solution
Go
func Contains[T comparable](s []T, v T) bool {
	for _, item := range s {
		if item == v {
			return true
		}
	}
	return false
}

func MaxOf[T cmp.Ordered](a, b T) T {
	if a > b {
		return a
	}
	return b
}

comparable allows ==, and cmp.Ordered allows < and >. The compiler infers T from the arguments, so the calls look like normal function calls. (The standard library already has slices.Contains and the builtin max.)

28. A generic Set (Advanced)

Implement Set[T comparable] with NewSet(vals ...T), Add, Has and Len. Duplicates must be stored once. Back it with a map[T]struct{}.

Go Exercise 28: A generic Set

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Show solution
Go
func NewSet[T comparable](vals ...T) *Set[T] {
	s := &Set[T]{items: make(map[T]struct{})}
	for _, v := range vals {
		s.Add(v)
	}
	return s
}

func (s *Set[T]) Add(v T) { s.items[v] = struct{}{} }

func (s *Set[T]) Has(v T) bool {
	_, ok := s.items[v]
	return ok
}

func (s *Set[T]) Len() int { return len(s.items) }

The empty struct struct{} takes no memory, so the map is used only for its keys. Writing to a nil map panics, so NewSet must create the map; this is why constructors exist for types whose zero value is not ready to use.

Concurrency

These practice goroutines, channels, the sync package and concurrency patterns.

29. Squares in parallel (Intermediate)

Write squares(nums []int) []int that squares every number in its own goroutine. The result must have the same order as the input. Wait for all goroutines before returning.

Go Exercise 29: Squares in parallel

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Show solution
Go
func squares(nums []int) []int {
	result := make([]int, len(nums))
	var wg sync.WaitGroup
	for i, n := range nums {
		wg.Go(func() {
			result[i] = n * n
		})
	}
	wg.Wait()
	return result
}

Each goroutine writes only its own slot result[i], so no lock is needed and the order is preserved. Since Go 1.22 each loop iteration has its own i and n, so the closures capture the right values. wg.Go (Go 1.25) combines Add(1), go and Done().

The solution also imports sync.

30. A two-stage pipeline (Advanced)

Write gen(nums ...int) <-chan int, which sends the numbers on a channel and then closes it, and sq(in <-chan int) <-chan int, which sends the square of every value it receives and closes its output when the input is closed. Each function starts its own goroutine.

Go Exercise 30: A two-stage pipeline

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Show solution
Go
func gen(nums ...int) <-chan int {
	out := make(chan int)
	go func() {
		defer close(out)
		for _, n := range nums {
			out <- n
		}
	}()
	return out
}

func sq(in <-chan int) <-chan int {
	out := make(chan int)
	go func() {
		defer close(out)
		for v := range in {
			out <- v * v
		}
	}()
	return out
}

Every stage closes the channel it created when its input is exhausted, and range over a channel ends on that close, so the shutdown flows from the first stage to the last without any extra signal. Forgetting a close would make the final range wait forever and Go would report a deadlock.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In exercise 18, removeAt(original, 0) is called and the caller prints original afterwards. Why does original change?

    A slice is a small header (pointer, length, capacity). The copy passed to the function still points at the caller's array, so shifting elements in it is visible outside. The header itself is a copy: the caller's length does not change.
  2. 2. Why does a method such as Scale in exercise 20 need a pointer receiver?

    With a value receiver the method works on a copy of the struct. Only a pointer receiver can modify the caller's value.
  3. 3. Which statement about recover (exercise 26) is true?

    recover returns the panic value only when called from a deferred function while the program is panicking. Elsewhere it returns nil.
  4. 4. What does errors.As(err, &ve) do when ve is a *ValidationError?

    errors.Is compares with a specific error value; errors.As looks for an error of a given type anywhere in the chain and assigns it to the variable.
  5. 5. In the pipeline of exercise 30, what happens if gen forgets to close its channel?

    range over a channel only ends when the channel is closed. Without a close, the stages wait for each other and Go stops the program with fatal error: all goroutines are asleep - deadlock!.

Summary

  • Small functions with a clear contract (inputs, results, errors) are easiest to get right; test the empty and the unusual inputs first.
  • Slices share memory, maps are unordered, and strings are bytes: most surprises come from one of these three.
  • Pointer receivers change the original, value receivers work on a copy; interfaces are satisfied implicitly.
  • Wrap errors with %w, inspect them with errors.Is and errors.As, and keep recover for boundaries.
  • Concurrent code needs a way to wait (WaitGroup), a way to finish (close) and no shared writes without a lock.
  • When you get stuck, run go vet mentally: read the compiler message, print the values and shrink the example. Then look at the interview questions to see which of these ideas employers ask about.

Next: Go Interview Questions