I don't understand why Result
exists in Rust. I can see how Option
can be useful, but using Result
just seems to complicate code unnecessarily.
Consider the following example:
#[derive(PartialEq, Eq, Debug)]
enum MyErr {
None,
FailOne,
}
fn returns_tuple() -> (u8, MyErr) {
// (1, None) // <-- Success path
(0, MyErr::FailOne)
}
fn returns_result() -> Result<u8, MyErr> {
// Ok(1) // <-- Success path
Err(MyErr::FailOne)
}
#[test]
fn test_check_return_values() {
let x = returns_result();
if x.is_ok() {
println!("result: Is OK: {}", x.unwrap()); // <-- Must use unwrap
} else {
match x.err().unwrap() { // <-- Again, unwrapping
MyErr::None => {}, // Required for match
MyErr::FailOne => println!("result: Failed One"),
}
}
}
#[test]
fn test_check_return_values_2() {
let (y, err) = returns_tuple();
match err {
MyErr::None => println!("tuple: Is OK: {}", y),
MyErr::FailOne => println!("tuple: Failed one"),
}
}
The only thing I can see is that it minorly increases the convenience of function writers, as you can simply call Ok()
and Err()
to return results.
I've seen some people saying its so you can use conditions, but that's not true at all; you can use conditions perfectly well using tuples. (Note — "conditions" were a feature of Rust that were removed before 1.0)
I've also seen some people saying that Result
is more performant that returning a tuple, but Result
is a tuple, so I don't see how this can be the case.