Result Type Alias Pins One Error Type

Shadow the std Result with type Result<T> = Result<T, E> so every fallible signature in a module shares one error type.

RustResilience

Code

rustsnippet
25 lines
use std::num::ParseIntError;

// 项目内统一错误别名:所有可失败签名只写 Result<T>
type Result<T> = std::result::Result<T, ParseIntError>;

fn parse_limit(raw: &str) -> Result<u32> {
    Ok(raw.parse::<u32>()?)
}

fn parse_port(raw: &str) -> Result<u16> {
    Ok(raw.parse::<u16>()?)
}

fn main() {
    match parse_limit("256") {
        Ok(limit) => println!("limit = {limit}"),
        Err(e) => println!("bad limit: {e}"),
    }

    // u16 溢出:PosOverflow,错误经 ? 从 parse 直接传播到调用方
    match parse_port("99999") {
        Ok(port) => println!("port = {port}"),
        Err(e) => println!("bad port: {e}"),
    }
}

How it works

One way to read it: the functions parse_limit, parse_port and main, doing all the work.

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.

Points of care

  • Install nothing — the snippet never steps outside the standard library.
  • Errors travel through Result; if you drop the ? operators while adapting, each call site needs its own match.

Putting it to use

The main signature reads fn parse_limit(raw: &str) -> Result<u32>

Look for the limit =, bad limit:, port = prefixes when the file runs; they tie each line to its step.

main sequences parse_limit and parse_port; executing the file runs that flow once.

Core lines

fn parse_limit(raw: &str) -> Result<u32> {
Ok(raw.parse::<u32>()?)
}
fn parse_port(raw: &str) -> Result<u16> {
Ok(raw.parse::<u16>()?)
}
match parse_port("99999") {
Ok(port) => println!("port = {port}"),
Err(e) => println!("bad port: {e}"),
}

Interactive Tools for This Topic

FAQ

How should callers handle failures?
As data, not exceptions: `Result` makes the caller handle both arms.
What does Result Type Alias Pins One Error Type print when run?
No setup needed: run the file and look for labeled lines like `limit =`, `bad limit:`, `port =` in the output.