Skip to main content
Module 2 · Lesson 3 of 58/50 in the course~10 min
Module lessons (3/5)

for...range

Lesson preview5 hands-on exercises readyCourse Go · Module 2 — Flow Control

Iterate over slice, map and strings; the returned value is a copy, when ignoring index or value with _.

What you'll learn in this lesson

  • Idiomatically iterate over slices, arrays, maps, strings, and channels using for ... range.
  • Understand why on string the range loop decodes UTF-8 runes while indexing reads bytes.
  • Avoid the copy bug on the second value of range when you want to edit a slice.

Overview

for ... range automatically adapts its behavior to the type of collection it is iterating over.

On slices and arrays range produces (indice, copia_elemento). Changing the iteration variable only changes the local copy, not the element inside the slice:

Sections covered in this lesson

  1. 1Range on slice and array: copy the value
  2. 2Range at map: Intentional random order
  3. 3Range at string: Unicode runes, not raw bytes
  4. 4Range on channel
  5. 5Guided practice
  6. 6Check for understanding
Pro Lesson · Module 2 — Flow Control

Unlock "for...range" and the full Course Go curriculum

Iterate over slice, map and strings; the returned value is a copy, when ignoring index or value with `_`.

Unlock all 5 hands-on exercises in this lesson plus every advanced WebAssembly module with automated checks.

  • Instant access to all advanced modules in Course Go plus 17 more courses
  • Hands-on browser exercises with automated test suites and solutions
  • 14-day money-back guarantee processed via Paddle.com

14-day guarantee · Cancel anytimeModule 1, all 18 interactive games, and cheatsheets are always free.