Option Is A Zero Or One Iterator
Iterate an Option directly: Some yields one element, None yields none, and flatten collapses Option layers inside pipelines.
Code
fn main() {
// Option 实现了 IntoIterator:Some 产出 1 个元素,None 产出 0 个
let hit = Some("cache-a");
for value in hit {
println!("for over Some: {value}");
}
let miss: Option<&str> = None;
let collected: Vec<&str> = miss.into_iter().collect();
println!("collect over None: {collected:?}");
let none_sum: u64 = None::<u64>.into_iter().sum();
println!("sum over None: {none_sum}");
// flatten 一次性抹平迭代器管道里的 Option 层
let checks = [Some(42), None, Some(7)];
let values: Vec<i32> = checks.into_iter().flatten().collect();
println!("flattened: {values:?}");
}How the snippet works
Under the hood: the function main.
for value in hit is the loop that carries the per-item work.
What to watch for
- No external packages — everything relies on the language’s built-in APIs.
Applying it
Signature: fn main()
The file announces its steps in the output: for over Some:, collect over None:, sum over None:.
Statements that matter
let none_sum: u64 = None::<u64>.into_iter().sum();
let checks = [Some(42), None, Some(7)];
let values: Vec<i32> = checks.into_iter().flatten().collect();
Interactive Tools for This Topic
FAQ
- What does Option Is A Zero Or One Iterator print when run?
- Invoke the file as-is — the `for over Some:`, `collect over None:`, `sum over None:` prefixes identify which step printed each line.
Report a problem with this exampleOpens a pre-filled issue on GitHub.