November 2017
Intermediate to advanced
264 pages
5h 45m
English
Now, we will see some examples that show why iterators are so useful. Iterators are lazy and have to be activated by invoking a consumer to start using the values. Let's start with a range of the numbers from 0 to 999 included. To make this into a vector, we apply the function collect() consumer:
// see code in Chapter 5/code/adapters_consumers.rs
let rng = 0..1000;
let rngvec: Vec<i32> = rng.collect();
// alternative notation:
// let rngvec = rng.collect::<Vec<i32>>();
println!("{:?}", rngvec);
This prints out the range (we shortened the output with...):
[0, 1, 2, 3, 4, ... , 999]
The function collect() loops through the entire iterator, collecting all of the elements into a container, here of type Vec<i32>. That ...
Read now
Unlock full access