- all
- iter
- into_iter
Iterator: all the elements
- all - calls a closure on every element of the iterator and if the closure returns true for every element then the expression returns true.
- See the documentation of the all method.
- iter iterates over borrowed references and thus we need to dereference the variables with *, but we can continue useing the original vector.
- into_iter iterates over the real values and thus we cannot use the original vector any more.
- The last example shows that the iteration will stop when it encounters the first false.
examples/iterators/all/src/main.rs
fn main() { let numbers = vec![23, 7, 12, 8]; if numbers.iter().all(|num| *num > 0) { println!("Positive numbers"); } if numbers.iter().all(|num| *num >= 10) { println!("Double digit numbers"); } if numbers.into_iter().all(|num| num > 0) { println!("Positive numbers"); } // use of moved value: `numbers` // if numbers.into_iter().all(|num| num >= 10) { // println!("Double digit numbers"); // } let numbers = vec![23, 12, 7, 8]; if numbers.iter().all(big) { println!("Double digit numbers"); } if numbers.into_iter().all(|num| { println!("Checking {num}"); num >= 10 }) { println!("Double digit numbers"); } } fn big(num: &i32) -> bool { println!("Checking in big {num}"); *num >= 10 }
Positive numbers Positive numbers Checking 23 Checking 12 Checking 7