-
Book Overview & Buying
-
Table Of Contents
Rust Essentials - Second Edition
By :
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 container does not have to be an iterator. Notice that we indicate the item type of the vector with Vec<i32>, but we could have also written it as Vec<_>. The notation collect::<Vec<i32>>() is new, it indicates...
Change the font size
Change margin width
Change background colour