Slice Contains Membership And Order Checks
slice::contains answers membership with PartialEq, iter().any generalizes to predicates, and windows() plus any() matches ordered subsequences.
Code
fn main() {
let deployed = ["api", "web", "worker"];
// slice::contains answers membership with PartialEq elementwise
println!("has worker: {}", deployed.contains(&"worker"));
println!("has cache : {}", deployed.contains(&"cache"));
// iter().any generalizes membership to any predicate
println!("any starts with w: {}", deployed.iter().any(|name| name.starts_with('w')));
// windows() + any() matches ordered consecutive subsequences
let forward = ["web", "worker"];
let backward = ["worker", "web"];
println!("web then worker: {}", deployed.windows(2).any(|w| w == &forward[..]));
println!("worker then web: {}", deployed.windows(2).any(|w| w == &backward[..]));
}What the code does
Structurally, expect the function main and nothing else.
Points of care
- The import surface (if any) is all standard library, all versioned with the language itself.
Applying it
Signature: fn main()
Output lines are prefixed (has worker:, has cache :, any starts with w:), making each step’s effect easy to spot.
Statements that matter
let deployed = ["api", "web", "worker"];
let backward = ["worker", "web"];
let forward = ["web", "worker"];
Interactive Tools for This Topic
FAQ
- What does Slice Contains Membership And Order Checks print when run?
- Run it as a complete program — the output lines carry labels such as `has worker:`, `has cache :`, `any starts with w:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.