It would be great if instead of nesting a dozen of scopes, conditional branches and loops could be merged. This also adds a way for for
loops to have a return type with break
. Consider the following example:
// Loop over elements, if nothing is found jump to `else`
let foo = for v in vec.iter() {
if v.is_truthy() { break Some(v); }
} else { None }
Consider the type theory behind loop
: Per default, a loop without breaks does not return, its' type is "never", or in Rust notation, !
. A for loop cannot act as a loop, because it has two break points: The keyword break
, or end of loop. This suggestion attempts to resolve this issue, by allowing a break to have a return type, however in that case requiring the conditional coverage. The assertion is, that an iteration can yield with two ways mentioned above, and each is given the unit type ()
per default. If both don't match, common Rust rules for scope returns apply.
let foo = for x in vec![0, 1, 2].iter() { break Some(x) }
// ^^^ type of foo cannot be implied from the context
// ^^^ The for loop returns of type Option<i32>, but case "end of loop" was not covered
// ^^^ help: consider adding 'else'
The same should work with a for - else ( for - else {} )
block. The parentheses are utility here to mark the way Rust should interpret this.
The other variant is, to begin with a condition, and then iterate:
let foo = if bar { // <- assertion
gum
} else for ... { // <- actual loop
break mug
} else { // <- end of unbroken loop condition
smug
}