Rust Programming: Matching on Different Errors

0

Matching on different errors in Rust is a way to handle different types of errors in different ways. This is done using the match expression.

Here is a example of matching on different errors in Rust:

Rust
use std::io::{Error, ErrorKind};

fn main() {
    let result = try_to_read_file("hello.txt");

    match result {
        Ok(contents) => println!("The contents of the file are: {}", contents),
        Err(error) => match error.kind() {
            ErrorKind::NotFound => println!("The file does not exist."),
            ErrorKind::PermissionDenied => println!("You do not have permission to read the file."),
            _ => println!("An unknown error occurred: {}", error),
        },
    }
}

fn try_to_read_file(filename: &str) -> Result<String, Error> {
    let file = std::fs::File::open(filename)?;
    let mut contents = String::new();
    std::io::Read::read_to_string(&mut file, &mut contents)?;
    Ok(contents)
}

This code will attempt to read the file hello.txt. If the file does not exist, the code will print a message to the console and exit. If the user does not have permission to read the file, the code will also print a message to the console and exit. If any other error occurs, the code will print the error message to the console and continue.

Matching on different errors can be useful for handling different types of errors in different ways. For example, you may want to log different types of errors to different places, or you may want to handle some errors gracefully and continue executing your program, while handling other errors by exiting your program.

Post a Comment

0Comments
Post a Comment (0)