Collect Into Option All Or Nothing

collect::<Option<Vec<_>>> returns None at the first None, so parsing a list of digits or fields fails as a whole without manual early exits.

RustData Integrity

Code

rustsnippet
17 lines
fn main() {
    // 逐字符解析:任何非数字字符让整个结果失败
    for input in ["2048", "0x1f"] {
        let digits: Option<Vec<u32>> = input.chars().map(|c| c.to_digit(10)).collect();
        match digits {
            Some(nums) => println!("{input} -> {nums:?}"),
            None => println!("{input} -> non-digit, abandoned as a whole"),
        }
    }

    // collect::<Option<_>> 遇到第一个 None 就整体返回 None
    let valid: Option<Vec<u32>> = ["3", "14", "15"].iter().map(|s| s.parse::<u32>().ok()).collect();
    println!("valid: {valid:?}");

    let broken: Option<Vec<u32>> = ["3", "x", "15"].iter().map(|s| s.parse::<u32>().ok()).collect();
    println!("broken: {broken:?}");
}

How it works

All of the logic lives in the function main.

for input in ["2048", "0x1f"] is where the per-item work happens. A match enumerates the value’s possible shapes, and the compiler rejects any arm you forget.

Points of care

  • The runtime is the only requirement — no packages, no install.

Using it

Signature: fn main()

The run emits 2 labeled sections — valid:, broken: — one per step.

Key statements

let valid: Option<Vec<u32>> = ["3", "14", "15"].iter().map(|s| s.parse::<u32>().ok()).collect();
let broken: Option<Vec<u32>> = ["3", "x", "15"].iter().map(|s| s.parse::<u32>().ok()).collect();
let digits: Option<Vec<u32>> = input.chars().map(|c| c.to_digit(10)).collect();

Interactive Tools for This Topic

FAQ

What does Collect Into Option All Or Nothing print when run?
No setup needed: run the file and look for labeled lines like `valid:`, `broken:` in the output.