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
}
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)?)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With