Crate for_else

Source
Expand description

for-else - Enhanced loop control in Rust

This crate provides a procedural macro, for_!, that enhances the behavior of the standard for loop in Rust. It allows for an additional else block that gets executed if the loop completes without encountering a break statement.

§Usage

Add the crate to your Cargo.toml dependencies and import the macros:

cargo add for-else

In your Rust code:

use for_else::for_;

// not the best way to test primality, just for demonstration
fn is_prime(n: u32) -> bool {
    if n <= 1 {
        return false;
    }
    for i in 2..n {
        if n % i == 0 {
            return false;
        }
    }
    true
}

for_! { n in 2100..=2110 {
    if is_prime(n) {
        println!("Found a prime number: {}", n);
        break;
    }
} else {
    println!("No prime numbers found in the range.");
}}

In this example, the program searches for the first prime number in the range [2100, 2110]. If a prime is found, it prints out the number. If no prime is found in the range, the else block within the for_! macro is executed, notifying the user.

See the for_! macro documentation for more detailed examples and usage information.

Macros§

for_
The for_! procedural macro with enhanced loop control.
while_
The while_! procedural macro with enhanced loop control.