liveBook · Manning

Diverging code

As explained in Learn Rust in a Month of Lunches

Diverging code is Rust code whose execution does not continue to the following statement because it exits the current control-flow path.

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:

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

How Learn Rust in a Month of Lunches covers it

How deep it goes
Defines divergence and demonstrates continue, break, and return, but does not develop compiler internals.
Examples
Demonstrates vector lookup with Some and None, loop continuation, and loop termination with break.
What it assumes
Assumes basic Rust control flow and pattern matching while introducing the role of Option values and let-else.
What you can do after
Apply diverging code in let-else blocks to preserve bindings after unsuccessful pattern matches.
How it connects
Connects diverging code to let-else, pattern matching, Option, loops, and early return.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Rust in a Month of Lunches. The section links point to the parts of the book it draws on.