Range Bounds Half Open And Inclusive

Half-open .. ranges compose with len() while ..= keeps the end bound; ranges are values you can test with contains, is_empty, and rev.

RustData Integrity

Code

rustsnippet
25 lines
fn main() {
    // half-open: excludes the end, so it composes with len()
    let letters = ['a', 'b', 'c', 'd', 'e'];
    for i in 0..letters.len() {
        print!("{} ", letters[i]);
    }
    println!();

    // ..= is the inclusive form, so 'a'..='e' covers five chars
    let mut inclusive = String::new();
    for ch in 'a'..='e' {
        inclusive.push(ch);
    }
    println!("inclusive: {inclusive}");

    // ranges are values: contains and is_empty test bounds without looping
    let working = 18..=65;
    println!("contains 30: {}", working.contains(&30));
    println!("contains 70: {}", working.contains(&70));

    // rev walks the same bounds backwards; start > end is empty, not an error
    let countdown: Vec<i32> = (1..=3).rev().collect();
    println!("rev: {countdown:?}");
    println!("5..1 is_empty: {}", (5..1).is_empty());
}

How the snippet works

Range Bounds Half Open And Inclusive is built around the function main.

Iteration happens inside for i in 0..letters.len() — everything outside it runs once.

Watch out for

  • Copy, run: the standard library answers every call in the file.

Using it

The main signature reads fn main()

The run emits 5 labeled sections — inclusive:, contains 30:, contains 70:, rev:, 5..1 is_empty: — one per step.

Key statements worth quoting

let countdown: Vec<i32> = (1..=3).rev().collect();

Interactive Tools for This Topic

FAQ

What does Range Bounds Half Open And Inclusive print when run?
The script runs standalone; its 5 labeled outputs include `inclusive:`, `contains 30:`, `contains 70:`.