bhylu.com

Advertisements

Rust Result and Error Handling

Return a reason when a count fails validation.

How it works

Result separates a successful value from an error value. Unlike Option, it can tell the caller why an operation was refused. Parse external text and apply business bounds before using the result. Keep error messages useful but avoid leaking private input or credentials. A fallible interface lets a caller report, retry or reject deliberately instead of crashing unexpectedly.

Run the code

Reviewed with Rust 1.97.0, edition 2024, using the standard library only. Save the complete download as lesson-name.rs in a separate learning folder, compile with rustc --edition=2024 lesson-name.rs and run the resulting program (lesson-name.exe on Windows). Use the actual lesson filename. The final project includes complete Cargo package files; run cargo test --offline and cargo run --offline from that separate package folder. There is no Rust browser runner; PHP, Apache and MySQL are not needed.

This complete example was executed in the stated local review environment.

Download complete source

Example

result.rs

fn main() {
    fn count(text: &str) -> Result<u32, &'static str> {
        let value = text.parse::<u32>().map_err(|_| "invalid integer")?;
        if value > 100 { return Err("count too large"); }
        Ok(value)
    }
    assert_eq!(count("8"), Ok(8));
    assert_eq!(count("bad"), Err("invalid integer"));
    assert_eq!(count("101"), Err("count too large"));
    println!("Valid count accepted; format and range errors distinguished");
}

Expected result

Valid count accepted; format and range errors distinguished

Parsing and the range check are separate failure categories. The ? operator propagates the mapped parse error and the explicit return handles the business maximum. The fixture allows zero; a different use case should change that rule and its tests together. No external file or service is involved.

Primary technical reference: Rust documentation.