Elvis operator for Rust

Syntax sugar is difficult to discuss because we all have different tolerance thresholds to glucose.

On this particular occurrence I'd fall in the camp of using a macro to start experimenting with the syntax. Ideally, it would be a postfix macro as already suggested in the thread, but barring them we could have:

unwrap_or_else!(lhs, rhs)

expand to what is presented in the first post.

In a previous post I already suggested using a macro to emulate let... else patterns, I think we could follow the same approach here. Maybe have a crate with some of these "useful control flow" macros, and see where we can go from there?

This is kind of a tangent, but I would be interested to read such code and see how readability is improved by banning these keywords. For instance without early returns, how do you express the following pattern without rightward drift:

if not some_precondition(inputs) {
    return;
}
// proceed in the rest of function assuming some_precondition(input) is met

?

Similarly, without catch_unwind, how do you catch panics from e.g. dependencies you don't fully control, and that should be allowed to fail in unexpected ways without tearing down you whole application? Or, how do you prevent your own application to unwind into FFI should it encounter a panic, which is UB? (I agree catch_unwind shouldn't be used for "normal control flow" though, but I guess most people here agree on that particular point)

4 Likes