rust error handling in rust

In Rust, error handling is typically done using the Result enum or the ? operator.

Here is an example of error handling in Rust:

main.rs
use std::fs::File;
use std::io::Error;

fn read_file_content(file_path: &str) -> Result<String, Error> {
    let mut file = File::open(file_path)?;
    
    let mut content = String::new();
    file.read_to_string(&mut content)?;
    
    Ok(content)
}

fn main() {
    match read_file_content("example.txt") {
        Ok(content) => println!("File content: {}", content),
        Err(err) => eprintln!("Error reading file: {}", err),
    }
}
443 chars
19 lines

In the example above:

  • The read_file_content function reads the content of a file specified by file_path and returns a Result<String, Error>.
  • The main function then calls read_file_content and matches on the returned Result, printing the file content if it was read successfully, or an error message if an error occurred.

You can use the Result and ? operator in combination with match expressions to propagate errors up the call stack in a concise and safe way.

related categories

gistlibby LogSnag