[rust-dev] Let’s avoid having both foo() and foo_opt()

Timothy Jones git at zimothy.com
Tue Jan 7 21:46:30 PST 2014

On 8/01/2014, at 3:39 pm, Nick Cameron <lists at ncameron.org> wrote:

> I think that you eventually have to deal with the Some or None-ness of an expression is an advantage of the ? operator, it means you can't ignore failure, but you don't have to deal with it at every step of a compound expression. Using an operator for unwrap has the same disadvantage as plain unwrap - it lets you ignore the failure case.

It's also worth pointing out that ? and do-notation solve different problems. ? is addressing that there's no partial application of the dot operator, so you can't write `maybe.and_then(.next)`. In do-notation, you'd still have to name the value inside the option.

You can produce a limited form of the refutable do-notation with a macro:

macro_rules! refute (
    (let $bind:pat = $val:expr; $(let $rbind:pat = $rval:expr);+; $result:expr) =>
    (match $val {
        $bind => refute!($(let $rbind = $rval);+; $result),
        fail => fail
    (let $bind:pat = $val:expr; $result:expr) =>
    (match $val {
        $bind => $result,
        fail => fail

fn add_opts(x: Option<int>, y: Option<int>) -> Option<int> {
        let Some(a) = x;
        let Some(b) = y;
        Some(a + b)

Chaining the ? operator can't really be done in a tidy manner without having it be part of the language. `?.` has been really useful in CoffeeScript, and Rust has the advantage of being able to tie it into a trait and allow any relevant type to use it.


More information about the Rust-dev mailing list