snippetrustModeratepending
Rust Result combinators -- clean error handling chains
Viewed 0 times
Resultmapand_thenunwrap_orquestion markerror chain
rust
Problem
Chaining multiple fallible operations in Rust with match statements creates deeply nested code. Need a cleaner way to compose Result-returning functions.
Solution
Use Result combinators: map, and_then, unwrap_or_else, and the ? operator for clean error propagation.
Code Snippets
Result error handling with ? and combinators
use std::fs;
use std::num::ParseIntError;
#[derive(Debug)]
enum AppError {
Io(std::io::Error),
Parse(ParseIntError),
Validation(String),
}
impl From<std::io::Error> for AppError {
fn from(e: std::io::Error) -> Self { AppError::Io(e) }
}
impl From<ParseIntError> for AppError {
fn from(e: ParseIntError) -> Self { AppError::Parse(e) }
}
fn load_config(path: &str) -> Result<u32, AppError> {
let content = fs::read_to_string(path)?; // ? converts io::Error
let port: u32 = content.trim().parse()?; // ? converts ParseIntError
if port < 1024 {
return Err(AppError::Validation("Port must be >= 1024".into()));
}
Ok(port)
}
// Combinators
let port = load_config("port.txt")
.unwrap_or_else(|_| 8080); // fallback on any error
let doubled = load_config("port.txt")
.map(|p| p * 2); // transform success valueRevisions (0)
No revisions yet.