Idea: syntax sugar for else-less if blocks and Option<T>

Simply put,

let x: Option<i32> = if some_condition {
    5
};

could be desugared into

let x: Option<i32> = if some_condition {
    Some(5)
} else {
    None
};

Some(open_questions):

  • Is this intuitive?
  • Is this intuitive when coupled with keywords like "break" or "return"?
  • Does this conflict with existing language features?
  • How does it interact with the ? operator?
  • Are there better patterns to achieve this?

The biggest argument for this is that it massively simplifies a very common pattern.

The biggest argument against this is that return if, break if, and eventually yield if would imply a conditional return/break/yield, but are in fact unconditional and simply yield an Option value.

1 Like

This has been discussed before, and it is a breaking change because currently if without else results in (). This would break all code that has an if at the end of a function.

Alternative already available behind the bool_to_option feature:

let x = some_condition.then_some(5);
10 Likes

I've argued for this before, but this isn't possible entirely backwards compatibly. Perhaps with the next edition we could enable this (if we have a next edition)?

For some reason, let x: () = if false { () }; compiles just fine. This is required IIUC with the current semicolon omission rules to allow omitting the semicolon after a lone if statement.

EDIT NOTE: forgot about trailing if in a function. That makes this a bigger breaking change than just the assignment edge case.

It would still be possible by writing in some special rules for if statements rather than if expressions, but I don't think the complexity would really be worth it.

Minor correction, the unstable method is named bool::then:

let x = some_condition.then(5);
3 Likes

This is the old name. In the RFC it was agreed that then/then_with should be replaced by then_some/then. The nightly doc shows the renamed pair.

3 Likes

For completeness:

Although this might technically be achievable with an edition, the potential benefit is definitely far too small for the amount of breakage this would cause (based on edition breakage proposals we’ve accepted and rejected in the past).

And even if we could ignore the breakage, this sort of “Some-wrapping” may not even be desirable for the same reasons “Ok-wrapping” is often not considered desirable (I personally dislike both for the same reasons). Simply Googling “Ok-wrapping” should produce far more than enough detailed debate on that subject.

3 Likes