Iter

#009 Feb 2022

9. Inspecting iterator

Ever wondered how to print while iterating?

Use inspect.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
let cars = vec!["Skoda", "Ferrari", "Ford"];

let car_lenghts: Vec<u32> = cars
    .iter()
    .enumerate()
    .inspect(|(idx, s)| println!("{idx} - {s}"))
    .map(|(_, name)| name.len() as u32)
    .collect();

assert!( car_lenghts == vec![5,7,4
#008 Feb 2022

8. Drain

Use drain to remove specified range from a vector.

1
2
3
4
5
let mut a = vec![1,2,3,4,5];

let _ = a.drain(0..3);

assert!(a == vec![4,5]);

What is the difference to call into_iter which returns T ?

into_iter takes the collection by value and consumes it.

drain borrows mutable reference, and returns a drain iterator of elements. If such iterator is dropped without exhausting it, all elements are dropped.

#007 Feb 2022

7. iter() vs into_iter()

What is the difference between .iter() and .into_iter()?

iter yields &T

into_iter may yield any of T, &T or &mut T based on context.

1
2
3
4
5
6
7
8
9
let cars = vec!["Skoda", "Ferrari", "Ford"];

for car in cars.iter() {
    println!("{car}");
}

for car in cars.into_iter() {
    println!("{car}");
}

this works but …

This does not. This results in compile error because cars are moved due to into_iter call.

1
2
3
4
5
6
7
8
9
let cars = vec!["Skoda", "Ferrari", "Ford"];

for car in cars.into_iter() {
  println!("{car}");
}

for car in cars.iter() {
    println!("{car}");
}