Um momento
0x30Lesson 4 of 6

Repeat work with loops and slices

Use Go’s for loop and a flexible list of values.

14 min 4-question quiz 1 code exercise
By the end of this lesson you can
  • 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.

main.go
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}
Output
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.

Exercise 1

Sum a list of numbers

+25 XP

Read a count followed by that many integers, then print their sum. Use a for loop.

  • Three values
  • Negative value
main.go
Loading editor…

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…

Gostou da aula? 😆👍
Apoie nosso trabalho com uma doação: