January 2018
Beginner to intermediate
454 pages
10h 8m
English
The for loop is another form of loops that can be used in Rust. It is used to loop over elements of an iterator. An iterator is a structure that produces a sequence of value: it could produce the same value indefinitely or produce the elements of a collection. We can get an iterator from a slice, so let's do that to compute the sum of the elements in a slice:
let array = [1, 2, 3, 4]; let mut sum = 0; for element in &array { sum += *element; } println!("Sum: {}", sum);
The only surprising part here is * in sum += *element. Since we get a reference to the elements of the slice, we need to dereference them in order to access the integers. We used & in front of array to avoid moving it, indeed, we may still want to use this variable ...