Optional chaining

For non-professionals like me, it looks like o.and_then(|o| o.f()) works similiarly to o?.f() in JavaScript.

The callback does have to return an Option though... So if o.f() returns (), you can write it as Some(o.f()) depending on how you're using the expression:

struct C;

impl C {
    fn f(&self) {
        println!("o.f()");
    }
}

fn main() {
    let o = Some(C);
    o.and_then(|o| Some(o.f()));
}

I'm wondering if there's anything more concise too.

This question belongs on URLO, but o.and_then(|o| Some(...)) is equivalent to o.map(|o| ...).

2 Likes

Ok

Eventually: try { o?.f() }.

4 Likes

Sadly this can't be used as a statement usage very much. For example:

try { Some(C)?.f() };

This fails to compile, as it requires typing.

I'm not sure what you're proposing there. If you have a known Some(C), couldn't you write C.f() to do what you want?

I was answering the original question, for where you have an Option and want to call a method and get an Option. For that, if you don't want map you could (in the future) use try and ?.

Some(C) is just a placeholder in that case. It could be any Option from elsewhere.

Then try should work. It doesn't today, but that's part of why it isn't stable yet.

2 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.