How does Result work in Rust

Result is an enum with Ok and Err variants used to handle recoverable errors in Rust without crashing.

Result is an enum that represents either a successful value (Ok) or an error (Err), allowing you to handle recoverable errors explicitly. You use it by returning Ok(value) on success or Err(error) on failure, then matching on the result to decide the next step.

fn read_file(path: &str) -> Result<String, std::io::Error> {
    if path.is_empty() {
        return Err(std::io::Error::new(std::io::ErrorKind::InvalidInput, "path is empty"));
    }
    Ok("file content".to_string())
}

fn main() {
    match read_file("data.txt") {
        Ok(content) => println!("Got: {}", content),
        Err(e) => println!("Error: {}", e),
    }
}