Any And All Short Circuit On Iterators
any and all stop consuming the iterator at the first decisive element, observable by logging how many items each visit actually touches.
Code
fn main() {
let numbers = [2, 4, 5, 8, 10];
let mut visited = 0;
// any 在第一个 true 处停:5 之后不再被消费
let has_odd = numbers.iter().inspect(|_| visited += 1).any(|&n| n % 2 == 1);
println!("any visited {visited} items, has_odd: {has_odd}");
visited = 0;
// all 在第一个 false 处停:5 之后不再被消费
let all_even = numbers.iter().inspect(|_| visited += 1).all(|&n| n % 2 == 0);
println!("all visited {visited} items, all_even: {all_even}");
visited = 0;
// 谓词永不成立时 any 消费全部元素后返回 false
let none_big = numbers.iter().inspect(|_| visited += 1).any(|&n| n > 100);
println!("any visited {visited} items, none_big: {none_big}");
}How it works
The moving parts are the function main.
Caveats
- No dependencies section needed; the standard library is the whole story.
Using it
Signature: fn main()
The run prints any visited, all visited — each prefix names the step that produced it.
Key statements
let all_even = numbers.iter().inspect(|_| visited += 1).all(|&n| n % 2 == 0);
let has_odd = numbers.iter().inspect(|_| visited += 1).any(|&n| n % 2 == 1);
let none_big = numbers.iter().inspect(|_| visited += 1).any(|&n| n > 100);
Interactive Tools for This Topic
FAQ
- What does Any And All Short Circuit On Iterators print when run?
- The script runs standalone; its 2 labeled outputs include `any visited`, `all visited`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.