Rfcs: return ... if ...

Created on 20 Jul 2017  路  5Comments  路  Source: rust-lang/rfcs

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);
T-lang

Most helpful comment

@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.

All 5 comments

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.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

torkleyy picture torkleyy  路  3Comments

mahkoh picture mahkoh  路  3Comments

silversolver1 picture silversolver1  路  3Comments

burdges picture burdges  路  3Comments

mqudsi picture mqudsi  路  3Comments