The for-range Construct

This lesson helps you learn how to run a loop on a slice using the for-range construct.

Introduction

This construct can be applied to arrays and slices:

for ix, value := range slice1 {
...
}

The first value ix is the index in the array or slice, and the second is the value at that index. They are local variables only known in the body of the for-statement, so value is a copy of the slice item at index ix and cannot be used to modify the slice!

Implementation of range on slices

The following is a simple program that iterates over a slice using the range construct.

Get hands-on with 1400+ tech skills courses.