Diverging code is code that lets execution escape before the next statement. In a let-else expression, the else block must diverge so the pattern-bound variable is guaranteed to exist afterward. section 5.2.3
Common ways to diverge include:
- continue skips to the next loop iteration. section 5.2.3
- break exits the loop before later statements run. section 5.2.3
- An early return leaves the current function. section 5.2.3
Using let-else with a loop
let Some(number) = my_vec.get(index) else { println!("No value"); break; }; println!("The number is: {number}");. When get returns None, the block prints a message and breaks; when it returns Some, number is available afterward. section 5.2.3
fn main() {
let my_vec = vec![2, 3, 4];
for index in 0..10 {
let Some(number) = my_vec.get(index) else { #1
println!("Looks like we got a None!");
println!("We can still do whatever we want inside this block");
println!("We just have to end with 'diverging code'");
print!("Because after this block, ");
println!("the variable 'number' has to exist");
println!("Time to break the loop now, bye");
break;
// return (); #2
};
println!("The number is: {number}");
}
}
Shows a complete let-else example with several statements inside the else block and break as its final diverging operation. section 5.2.3
