Iterator: all the elements
-
all
-
iter
-
into_iter
-
all- calls a closure on every element of the iterator and if the closure returnstruefor every element then the expression returnstrue. -
See the documentation of the all method.
-
iteriterates over borrowed references and thus we need to dereference the variables with*, but we can continue useing the original vector. -
into_iteriterates 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.
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