Non-returning ? operator

I'm trying out Rust at home and I wrote some code that looks like this.

let mut foo = ...; // foo: Option<T>
if let Some(ref mut f) = foo {
    f.bar();
}

// [...some code here...]

if let Some(ref mut f) = foo {
    f.baz();
}

I tried to replace the if-lets with foo?.bar(); and foo?.baz(); like I usually do in C# but then Rust correctly complains that the function doesn't return a Result or a Option or other type that implements Try (of course it does, since ? "short-circuits" the whole function).
Is there a macro or an operator that works similar to C# where it just ignores the rest of the expression like it were in a if-let?
Thanks.

There isn't an operator for it but maybe map is what you want:

foo.as_mut().map(|f| f.bar());

Although this could be confusing since it mixes functional and imperative styles.

1 Like

AFAIK, in Rust it would be idiomatic to call the methods on Option passing the closure or function pointer, like this:

fn use_opt_foo(mut foo: Option<Foo>) {
    foo.as_mut().map(Foo::bar);
    // some other code
    foo.as_mut().map(Foo::baz);
}

Playground illustrating the idea.

2 Likes

I disagree with using map for side-effects being idiomatic. I would go for the if let.

if let Some(foo) = &mut foo {
     foo.bar();
}
5 Likes

If try blocks are stabilized in the future, then you will be able to write this as:

try { f?.bar(); }
// ...
try { f?.baz(); }
7 Likes

It might be better to rethink things rather than try to write C# style in Rust.

Keep in mind the ? operator in Rust is not meant to be anything like as the ?. operator in C# (it isn't just ? as that is the ternary conditional operator, and ?? is the null coalescing operator).

Null propagation doesn't exist in Rust because Rust doesn't have nulls. The Option type is the closest thing to null and has several useful methods on it.

4 Likes

Thanks.
I didn't know about try blocks... They seem the closest as possible to that.
So it seems for the moment (until they're stabilized) map() is the only possible "shortcut".
@m51: I too think that if there are a lot of them probably rethinking about the code or refactoring it is better.