Any All Find And Position Predicates
Answer existence questions with any and all and locate items with find and position — all four stop at the first matching element.
Code
fn main() {
let statuses = [200u16, 204, 502, 404, 500];
// any:存在即真,遇到首个满足项就短路
let has_server_error = statuses.iter().any(|&s| s >= 500);
println!("any >= 500: {has_server_error}");
// all:全部满足才真
let all_handled = statuses.iter().all(|&s| s < 600);
println!("all < 600: {all_handled}");
// find:第一个满足项的值,Option 承载可能不存在
let first_4xx = statuses.iter().find(|&&s| (400..500).contains(&s));
println!("first 4xx: {first_4xx:?}");
// position:第一个满足项的下标
let at = statuses.iter().position(|&s| s >= 500);
println!("first >= 500 at index {at:?}");
// 找不到时 find 与 position 都得到 None
let teapot = statuses.iter().find(|&&s| s == 418);
println!("teapot: {teapot:?}");
}How the snippet works
Count the function main as the entire surface area of Any All Find And Position Predicates.
Applying it
Running the file prints labeled results such as any >= 500:, all < 600:, first 4xx: — each operation’s effect is visible in the output.
Statements that matter
let first_4xx = statuses.iter().find(|&&s| (400..500).contains(&s));
let has_server_error = statuses.iter().any(|&s| s >= 500);
let all_handled = statuses.iter().all(|&s| s < 600);
Interactive Tools for This Topic
FAQ
- What does Any All Find And Position Predicates print when run?
- Running the file directly is enough — expect labeled output lines such as `any >= 500:`, `all < 600:`, `first 4xx:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.