Infallible Errors Match To Nothing

u32::try_from(char) reports Infallible as its error type: an empty match compiles because that Err arm is logically unreachable and unwrap never panics.

RustData Integrity

Code

rustsnippet
17 lines
use std::convert::Infallible;

fn main() {
    // u32::try_from(char) 的错误类型是 Infallible:char 永远装得进 u32
    let parsed: Result<u32, Infallible> = u32::try_from('A');

    let code = match parsed {
        Ok(code) => code,
        // Infallible 没有任何值,空 match 就能通过编译:这个分支逻辑上不可达
        Err(infallible) => match infallible {},
    };
    println!("code: {code}");

    // Err 不可能存在,unwrap 也不会 panic
    let again = u32::try_from('€').unwrap();
    println!("euro: {again}");
}

How the snippet works

The working surface is the function main — everything else is wiring.

Fallible operations return Result, forcing the caller to handle both arms explicitly. Pattern matching via match forces each shape of the value to be handled.

What to watch for

  • No dependencies section needed; the standard library is the whole story.
  • Errors travel through Result; if you drop the ? operators while adapting, each call site needs its own match.

Applying it

Entry signature: fn main()

Look for the code:, euro: prefixes when the file runs; they tie each line to its step.

Statements doing the real work

let again = u32::try_from('€').unwrap();
let code = match parsed {
    Ok(code) => code,
    // Infallible 没有任何值,空 match 就能通过编译:这个分支逻辑上不可达
    Err(infallible) => match infallible {},
};

Interactive Tools for This Topic

FAQ

How does the code signal failure?
No panics — `Result` values carry the failure.
What does Infallible Errors Match To Nothing print when run?
The script runs standalone; its 2 labeled outputs include `code:`, `euro:`.