Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use empty Result in return?

Tags:

rust

I often see functions or methods returning Result<(), Error> like this:

fn f() -> Result<(), Error> {
    Ok(())
}

In other words such return returns nothing or an error. Why use Result in such situations but not an Option? I think Option would be more suitable, as it effectively returns None or value, in our example - None or an error.

fn f() -> Option<Error> {
    None
}
like image 448
Aleksey Kanaev Avatar asked Jul 17 '26 09:07

Aleksey Kanaev


1 Answers

Result represents success or failure; Option represents any optional value. When you’re trying to represent success or failure, even when you could use Option, Result is more appropriate.

Because Result is the type for a failure alternative, it’s also more easily used in checks for failure, like with the ? operator:

fn read_int() -> Result<u32, ReadIntError> {
    let mut buf = [0_u8; 10];
    read_line(&mut buf)?;  // <-- can’t do this if read_line returns
                           // Option<ReadError>
    Ok(parse_int(&buf)?)
}
like image 151
Ry- Avatar answered Jul 22 '26 13:07

Ry-



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!