Expand description
Exit early from a loop or labelled block.
Whenbreak is encountered, execution of the associated loop body isimmediately terminated.
A break expression is normally associated with the innermost loop enclosing thebreak but a label can be used to specify which enclosing loop is affected.
'outer:foriin1..=5{println!("outer iteration (i): {i}");'_inner:forjin1..=200{println!(" inner iteration (j): {j}");ifj >=3{// breaks from inner loop, lets outer loop continue.break; }ifi >=2{// breaks from outer loop, and directly to "Bye".break'outer; } }}println!("Bye.");When associated withloop, a break expression may be used to return a value from that loop.This is only valid withloop and not with any other type of loop.If no value is specified forbreak; it returns().Everybreak within a loop must return the same type.
let(muta,mutb) = (1,1);letresult =loop{ifb >10{breakb; }letc = a + b; a = b; b = c;};// first number in Fibonacci sequence over 10:assert_eq!(result,13);println!("{result}");It is also possible to exit from anylabelled block returning the value early.If no value is specified forbreak; it returns().
letinputs =vec!["Cow","Cat","Dog","Snake","Cod"];letmutresults =vec![];forinputininputs {letresult ='filter: {ifinput.len() >3{break'filterErr("Too long"); };if!input.contains("C") {break'filterErr("No Cs"); };Ok(input.to_uppercase()) }; results.push(result);}// [Ok("COW"), Ok("CAT"), Err("No Cs"), Err("Too long"), Ok("COD")]println!("{:?}", results)For more details consult theReference on “break expression” and theReference on “break andloop values”.