use std::fmt;
#[derive(Debug)]
enum MyError {
NotFound,
InvalidInput(String),
}
impl fmt::Display for MyError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
MyError::NotFound => write!(f, "Item not found"),
MyError::InvalidInput(msg) => write!(f, "Invalid input: {}", msg),
}
}
}
impl std::error::Error for MyError {}
fn find_item(id: i32) -> Result<String, MyError> {
if id == 0 {
Err(MyError::NotFound)
} else if id < 0 {
Err(MyError::InvalidInput("negative id".to_string()))
} else {
Ok("Item found".to_string())
}
}
fn main() {
match find_item(-1) {
Ok(item) => println!("{}", item),
Err(e) => println!("Error: {}", e),
}
}Defines a custom error enum with two variants, implements Display and Error traits, then uses it in a function returning Result to handle errors.