0
0
Rustprogramming~5 mins

Result enum in Rust

Choose your learning style9 modes available
Introduction

The Result enum helps your program handle success or failure clearly. It tells you if something worked or if there was an error.

When reading a file that might not exist.
When dividing numbers and you want to avoid dividing by zero.
When making a network request that could fail.
When parsing user input that might be wrong.
Syntax
Rust
enum Result<T, E> {
    Ok(T),
    Err(E),
}

T is the type for a successful value.

E is the type for an error value.

Examples
This shows a Result with an integer on success and a string on error.
Rust
let success: Result<i32, &str> = Ok(10);
let failure: Result<i32, &str> = Err("Oops");
This function returns Ok with the division result or Err with an error message.
Rust
fn divide(a: i32, b: i32) -> Result<i32, String> {
    if b == 0 {
        Err(String::from("Cannot divide by zero"))
    } else {
        Ok(a / b)
    }
}
Sample Program

This program tries to divide numbers safely. It prints the result if successful or an error message if not.

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!("Success: {}", value),
        Err(e) => println!("Error: {}", e),
    }

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

You can use match to check if a Result is Ok or Err.

Using Result helps avoid crashes by handling errors properly.

Summary

Result shows success or failure clearly.

Use Ok for success and Err for errors.

Handle Result with match to respond to each case.