0
0
Rustprogramming~5 mins

Handling errors with match in Rust

Choose your learning style9 modes available
Introduction

We use match to check if something worked or failed, so we can handle each case properly.

When reading a file and you want to do something different if it fails.
When converting text to a number and you need to handle invalid input.
When calling a function that might return an error and you want to respond accordingly.
When working with network requests that can succeed or fail.
When you want to show a message to the user depending on success or failure.
Syntax
Rust
match result {
    Ok(value) => {
        // code to run if result is success
    },
    Err(error) => {
        // code to run if result is error
    },
}

Ok means success and holds the value.

Err means failure and holds the error.

Examples
This prints the number if success, or the error message if failure.
Rust
let result: Result<i32, &str> = Ok(10);
match result {
    Ok(num) => println!("Success: {}", num),
    Err(e) => println!("Error: {}", e),
}
This handles the error case by printing the failure message.
Rust
let result: Result<i32, &str> = Err("Not a number");
match result {
    Ok(num) => println!("Got number: {}", num),
    Err(e) => println!("Failed: {}", e),
}
Sample Program

This program tries to divide numbers. It prints the result if division works, or an error message if it fails (like dividing by zero).

Rust
fn divide(a: i32, b: i32) -> Result<i32, String> {
    if b == 0 {
        Err(String::from("Cannot divide by zero"))
    } else {
        Ok(a / b)
    }
}

fn main() {
    let result = divide(10, 2);
    match result {
        Ok(value) => println!("Result is {}", value),
        Err(e) => println!("Error: {}", e),
    }

    let result2 = divide(5, 0);
    match result2 {
        Ok(value) => println!("Result is {}", value),
        Err(e) => println!("Error: {}", e),
    }
}
OutputSuccess
Important Notes

Always handle both Ok and Err to avoid crashes.

You can use _ to ignore the value if you don't need it.

Using match helps you clearly see what happens in success and error cases.

Summary

match lets you check if a result is success (Ok) or error (Err).

Handle both cases to keep your program safe and clear.

This is useful whenever something might fail and you want to respond properly.