Repeat work with loops and slices
Use Go’s for loop and a flexible list of values.
- Loop over input values and accumulate a result.
Go uses for for every kind of loop. Its three-part form has an initializer, condition, and update. A slice is a flexible view over a sequence; append adds values. Use range to visit each item without managing indexes yourself.
1package main
2
3import "fmt"
4
5func main() {
6 scores := []int{8, 7, 10}
7 total := 0
8 for _, score := range scores {
9 total += score
10 }
11 fmt.Println(total)
12}25
In a range loop, the first value is the index and the second is the element. Use _ when you do not need a returned value. Slices grow dynamically, unlike fixed-length arrays.
Key takeaways
Loop over input values and accumulate a result.
Go catches many mistakes while compiling.
Use small experiments to understand each new language feature.
Lesson quiz
4 questions · pass with 3 correct · up to 50 XP
Passing this quiz completes the lesson and keeps your streak going. Questions you miss come back in review sessions later.
Practice: write Go
Write Go in the editor and run it against sample input with a remote compiler. Your code is sent to Compiler Explorer to compile and run.
Sum a list of numbers
Read a count followed by that many integers, then print their sum. Use a for loop.
- Three values
- Negative value
Go is compiled and run by Compiler Explorer (godbolt.org), a free public service. Your source code and test input are sent to that service.
Questions about this lesson
Stuck? Ask. Figured something out? Share it. Explaining is one of the best ways to learn.
Loading posts…