Rust:Rust Break and Continue Statements with Loop Labels
Rust•Loop Control

Rust Break and Continue Statements with Loop Labels

break exits the loop; continue advances to next iteration. Use loop labels ('label:) to escape nested loops.

Syntax

if condition { break; } if condition { continue; }

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
breakKeywordTerminates loop execution.
continueKeywordSkips current iteration.

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing Rust locally:

fn main() {
    let readings = [22, 24, -1, 26, 999, 28];

    println!("Processing sensor readings:");
    for val in readings {
        if val < 0 {
            println!("  [SKIP] Glitch reading: {}", val);
            continue;
        }
        if val == 999 {
            println!("  [HALT] Sentinel 999 detected! Shutting down.");
            break;
        }
        println!("  [OK] Temperature: {}C", val);
    }
}
Expected Output:
Processing sensor readings:
  [OK] Temperature: 22C
  [OK] Temperature: 24C
  [SKIP] Glitch reading: -1
  [OK] Temperature: 26C
  [HALT] Sentinel 999 detected! Shutting down.

How It Works: Step-by-Step

  • Lines 7-10: continue skips -1.
  • Lines 11-14: break halts loop upon 999.

Key Concepts

  • continue skips straight to the next iteration.
  • break terminates only the innermost loop unless a label is specified.

Common Mistake: Placing break before necessary state mutations

Statements after break within the same block are unreachable.

❌ Incorrect
if done { break; count += 1; } // Warning: unreachable statement
✅ Correct
if done { count += 1; break; }

Related Rust Tutorials & Compiler

Run and test Rust on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

Rust Online Compiler