Allow reverse if including return. This would work similar to the let/if statement but have the following signature:
return val if expr;
This would allow for both easy parameter checking and one line return statements.
Some examples:
return Err(new Error("There must be at least 5 apples")) if apples < 5;
return Ok(None) if !ip_well_formed(&ip);
The problem with this is that it is incongruous with the way all other Rust code is written. Well it may be familiar to people coming from Ruby, I imagine programmers coming from other languages would be confused and surprised by it.
You can have one line return statements today already:
if expr { return val; }
This would add another way of doing the same thing without being more useful.
Adding on to what @mglagla said, we have:
return if expr { val } else { other_val };
And if the line is the last line of a function, the explicit return can be omitted.
Overall, this feels like it's solving an ergonomics problem that Rust doesn't have.
Wait @AndrewBrinker, so does that code already exist, I have not heard of it
@Nokel81 if blocks are expressions in Rust rather than statements, so they can be used in the same places as any other expression, e.g. let x = if true { 1 } else { 2 }; is also valid.
Most helpful comment
@Nokel81
ifblocks are expressions in Rust rather than statements, so they can be used in the same places as any other expression, e.g.let x = if true { 1 } else { 2 };is also valid.