[Rust] Result

고승우·2024년 7월 15일
0

Rust

목록 보기
11/16
post-thumbnail

Result

Rust doesn’t have exceptions. Instead, functions that can return result type like following code.

fn get_weather(location: LatLng) -> Result<WeatherReport, io::Error>

Result Type Aliases

Defining a public type std::io::Result<T> is an an alias for Result<T, E>.

pub type Result<T> = std::result::Result<T, Error>;

After that, you can define Result to return like this.

fn remove_file(path: &Path) -> Result<()>

Propagating Errors

? operator propagate errors up to the call stack. The behavior of ? depends on whether this function returns a success result or an
error result:

  • On success: unwrap the result to get success value inside.
  • On error: immediately returns from the enclosing function, passing the error result up the call chain. You can propagate errors like following code.
fn move_all(src: &Path, dst: &Path) -> io::Result<()> {
    for entry_result in src.read_dir()? {
        // opening dir could fail
        let entry = entry_result?; // reading dir could fail
        let dst_file = dst.join(entry.file_name());
        fs::rename(entry.path(), dst_file)?; // renaming could fail
    }
    Ok(()) // phew!
}

Working with Multiple Error Types

There are two ways to handle multiple error type.
1. Implement conversion: ? operator does automatic conversion using a standard method.

pub enum MyError {
    DatabaseError(Box<dyn Debug>),
    ZeroDivisionError,
    InternalServerError,
}

impl From<MyError> for std::io::Error{
    fn from(value:MyError) -> Self {
        match value {
            MyError::DatabaseError(_) => todo!(),
            MyError::ZeroDivisionError => todo!(),
            MyError::InternalServerError => todo!(),
        }
        todo!()
    }
}
  1. Define Generic Error: All of the standard library error types can be converted to the type Box<dyn std::error::Error + Send + Sync + 'static>.
type GenericError = Box<dyn std::error::Error + Send + Sync + 'static>;
type GenericResult<T> = Result<T, GenericError>;
profile
٩( ᐛ )و 

0개의 댓글