Can a `break` from a labeled loop return a value? If so, explain how and provide a code example.

Go & Rust interview question for Advanced practice.

Answer

No, a break from a labeled outer loop cannot directly return a value from that outer loop. Only an unlabeled loop can be an expression that returns a value. When you use break 'label value;, the value part is associated with an inner loop that you might be breaking from, but the label itself only directs the control flow to exit the outer loop. The value doesn't propagate up to the let binding of the outer loop. Clarifying Example: This code might look like it should work, but it will cause a compile error because the outer loop 'outer does not produce a value. rust // This code will NOT compile. fn main() { let result = 'outer: loop { loop { break 'outer 5; // Tries to return 5 from 'outer } }; // Compiler Error: break with value from a loop that is not labeled with 'outer } Correct Way to Achieve a Similar Goal: To get a value out of a nested loop structure, you must break the inner loop with a value, store it, and then break the outer loop. rust fn main() { let mut finalresult = 0; 'outer: loop { let innerresult = loop { // Some logic... break 10; // This value is returned from the inner loop }; finalresult = innerresult; break 'outer; // Now break the outer loop } println!("Final result: {}", finalresult); // Prints 10 }

Explanation

While a break 'label value; is syntactically valid and will compile, the value is returned from the inner loop, not the labeled outer loop. This is a subtle but important distinction in Rust's control flow.

Related Questions