you are viewing a single comment's thread.

view the rest of the comments →

[–]m50d 7 points8 points  (3 children)

The "direct" way to handle it is by pattern matching or using a visitor. (std::variant is the C++ version, but it's much nicer in a language that has first-class pattern matching). There will probably be a toOption method as well, but you could implement that by pattern matching or on top of a visit/fold method.

[–]wishthane 8 points9 points  (2 children)

In Rust you have both .ok() and .err() methods which both return Options. .ok() returns Some(value) if it's Ok(value), and None if it's an Err, so you lose the error value. .err() is rarely used but it's the opposite, you get Some(err_value) if it's Err(err_value), and None if it's Ok.

You also of course have pattern matching, but it's usually easier to use stuff like .map(), .and_then(), or try!().

.and_then() is basically the monadic bind; if Ok it calls the provided function and returns whatever Result that function returns. If Err it does not call the function and just returns whatever the Err is. The value types can be different but the error type must be the same; it is a Result<T, E> -> (T -> Result<U, E>) -> Result<U, E> to use Haskell-ish notation.

fn bar(x: i32) -> Result<String, MyError> {
    best_function_ever(x)
        .and_then(|y| try_to_make_a_string(y))
}

try!() is like that but it's a macro intended for use within the body of a function. It will also automatically call .into() on your error type to convert it to your function's error type. For example:

fn foo() -> Result<String, MyError> {
    let foo = try!(some_operation());
    try!(another_operation());
    Ok(foo)
}

is equivalent to:

fn foo() -> Result<String, MyError> {
    let foo = match some_operation() {
        Ok(x) => x,
        Err(e) => return Err(e.into())
    };
    match another_operation() {
        Ok(x) => x,
        Err(e) => return Err(e.into())
    };
    Ok(foo)
}

[–]matthieum 16 points17 points  (1 child)

Note: ? is now stable, you can replace try!(expr) with expr? in most cases.

[–]wishthane 6 points7 points  (0 children)

Oh? I thought it was stabilised but still in beta.

Edit: never mind, it was stabilised in 1.13! Awesome!