Code Example Template
let file: Result<String, std::io::Error> = std::fs::read_to_string("profile.json");

Deep-Dive System Documentation

Result: Robust Error Handling

In Rust, recoverable errors do not trigger runtime exceptions. Instead, functions return the Result<T, E> algebraic type.

Definition

enum Result<T, E> {
    Ok(T),
    Err(E),
}

Enforcing Error Resolution

The compiler marks Result with the #[must_use] attribute. If you invoke a function returning a Result and ignore the return value, it issues a compiler warning.

let file_result: Result<String, std::io::Error> = std::fs::read_to_string("profile.json");

match file_result {
    Ok(content) => println!("Config content: {}", content),
    Err(err) => eprintln!("Failed to load configuration: {}", err),
}

System Integration

When operating low-level system commands, map OS errors into Rust Result structs using std::io::Error::last_os_error(). This reads the underlying Win32 GetLastError code dynamically.


Useful Methods

.is_ok() -> bool

Returns true if the result is Ok.

let x: Result<i32, &str> = Ok(-3);
assert_eq!(x.is_ok(), true);

.unwrap() -> T

Extracts the success value. Use with caution: panics if the result is Err.

let x: Result<u32, &str> = Ok(2);
assert_eq!(x.unwrap(), 2);

.unwrap_or(default: T) -> T

Returns the contained Ok value or a provided default value.

let default_val = 50;
let x: Result<i32, &str> = Err("error");
assert_eq!(x.unwrap_or(default_val), 50);

.map<U, F>(op: F) -> Result<U, E> where F: FnOnce(T) -> U

Maps a Result<T, E> to Result<U, E> by applying a function to a contained Ok value, leaving an Err value untouched.

let val: Result<i32, &str> = Ok(4);
let doubled = val.map(|i| i * 2);
assert_eq!(doubled, Ok(8));

.map_err<F, O>(op: F) -> Result<T, O> where F: FnOnce(E) -> O

Maps a Result<T, E> to Result<T, O> by applying a function to a contained Err value, leaving an Ok value untouched. Useful for converting error types.

let val: Result<i32, i32> = Err(404);
let new_err = val.map_err(|e| format!("Error Code: {}", e));
assert_eq!(new_err, Err(String::from("Error Code: 404")));

Quick Reference Guide

let res: Result<i32, &str> = Ok(10);
if res.is_ok() { /* ... */ }