Inclusive char intervals

I've seen that now this handy code is allowed:

#![feature(inclusive_range_syntax)]

fn main() {
    for b in 0u8 ... 255u8 {
        println!("{}", b);
    }

    for bc in b'a' ... b'z' {
        print!("{} ", bc as char);
    }
    println!("");
}

(Some languages prefer to denote inclusive ranges with a syntax like "..>" or similar, to better distinguish it visually from the ".." syntax).

But I'd also like to avoid casts:

#![feature(inclusive_range_syntax)]

fn main() {
    for c in 'a' ... 'z' {
        print!("{} ", c);
    }
    println!("");
}

Is it planned to support this too?

https://github.com/rust-lang/rfcs/blob/master/text/1192-inclusive-ranges.md

Thank you for your answer. The RFC says:

'a'..'{' is equivalent to the inclusive range 'a'...'z': there's absolutely no reason that { is after z other than a quirk of the representation.

But in that page I can't see an answer to my question, if the support for 'a'...'z' is planned.

As you may already know, ranges of chars are tricky because not all 32-bit values represent valid Unicode characters. Because of this, char does not implement the Add trait which is required by the Iterator implementation for RangeInclusive.

The char-iter crate has a custom iterator which contains the necessary logic, so you can write:

for c in char_iter::new('a', 'z') {
    // ...
}

The Add trait is used only in the implementation of RangeInclusive::size_hint. Specialization might make it possible to provide an impl that only requires the Step trait (which isn’t implemented by char but could be), and add the size_hint only for types that implement Add.

3 Likes

Thank you, it's OK.