Skip to content

Checkpoint: Summarize a Slice

The Course
•
24 min study

Today's checkpoint asks for a function that works on any slice of numbers, including one with no numbers at all. That second case is the real test. A total that is right for three values but crashes or prints something odd for zero values would fail the first time a user starts a fresh log. Write the function so the empty case works without any special handling.

What you will use

  • A function with a slice parameter. The parameter type is []int, so the caller can pass any number of values. The result type is int.
  • An accumulator inside the function. sum starts at 0 and lives in the function body, so each call gets its own fresh total.
  • A range loop. for _, value := range values visits every item and ignores the index, which this task does not need.
  • return. The function hands the sum back, and main decides how to print it.
  • A slice literal as an argument. total([]int{10, 15, 25}) builds a slice and passes it in one expression. []int{} is an empty slice of the same type.

Plan before you type

  1. Write the signature first: a name, one parameter of type []int, and an int result.
  2. Inside the function, start a sum at zero, add each value with a range loop, and return the sum.
  3. In main, call the function twice and print each result on its own line.
  4. Predict both outputs before running. For the empty slice, ask: how many times does the loop body run, and what value does sum still hold?

Why the empty case needs no extra code

It is tempting to add if len(values) == 0 and return 0 early. That works, but it is not needed. A range loop over an empty slice runs its body zero times, so sum keeps its starting value of 0, which is exactly the right total. When the general rule already handles the edge case, an extra branch is just another line that could drift out of step with the rest.

Edge cases are worth a line of output

Printing the empty-slice result is part of the task on purpose. Get into the habit of calling a new function with the smallest input it should accept, such as an empty slice, a zero or a single item, before you trust it with ordinary data.

Mistakes worth checking for

  • The compiler reports missing return: the function's last statement is the loop, and nothing returns sum after it.
  • The compiler reports declared and not used: index: the loop keeps an index it never uses. Replace it with _.
  • The total is wrong when the slice has one item or none: sum started from the first item instead of 0, or the loop skipped an index. Start sum at 0 and range over every item.
  • The compiler reports cannot use []int{} (value of type []int) as int value: the parameter was declared as int instead of []int.
Exercise

Your turn

Write a total function that takes a slice of integers and returns their sum. Print the total of 10, 15, 25 and the total of an empty slice, on separate lines.

Your working space Go
package main

func main() {
	// Build your solution here.
}
Hint 1: the idea

A loop over an empty slice never runs, so the sum keeps its starting value.

Hint 2: a first step

Give the function a parameter of type []int.

Worked solution
Run the solution Go
package main

import (
	"fmt"
)

func total(values []int) int {
	sum := 0
	for _, value := range values {
		sum += value
	}
	return sum
}

func main() {
	fmt.Println(total([]int{10, 15, 25}))
	fmt.Println(total([]int{}))
}
Text
50
0

The empty slice gives 0 with no special case, because the loop body never runs.

Before Day 4

Check that you can do each of these without looking back:

  • Write the signature of a function that takes a slice of strings and returns a count.
  • Get the last item of any non-empty slice, and say what happens if the slice is empty.
  • Explain why for _, minutes := range sessions does not change sessions when you add to minutes.

Day 4 groups related values together. A struct gives one record several named fields, a slice of structs holds many records, and a map looks up a value by a key such as a title.

Was this article helpful?

Your response is saved on this device.