Ranges and ordering

Ranges and ordering

Range types and the Ordering enum.

Contents

NameSummary
OrderingThe result of a three-way comparison: what a <=> b evaluates to.
RangeA bounded range: a..b (exclusive end) and a..=b (inclusive end).
RangeFromA range with no end: a.., or .. as begin: 0 (a RangeFrom<usize>).
RangeToA range with no start: ..b or ..=b.

Ordering

enum Ordering derives i8

The result of a three-way comparison: what a <=> b evaluates to.

The discriminants are -1, 0 and 1. The relational operators are lowered from op <=>: a < b becomes ((a.op<=>(b)) as i8) < 0, with the original token compared against 0.

Example

struct Version { var major: i32 }

extend Version {
    fn op <=>(const self, const other: Version) -> Ordering {
        if self.major < other.major { return Ordering::Less }
        if self.major > other.major { return Ordering::Greater }
        return Ordering::Equal
    }
}

fn main() -> i32 {
    var a = Version { major: 1 }
    var b = Version { major: 2 }
    if (a <=> b) == Ordering::Less { return 0 }
    return 1
}

Ordering.Less

Less

The left operand orders before the right (-1).

Ordering.Equal

Equal

The operands are equivalent (0).

Ordering.Greater

Greater

The left operand orders after the right (1).

Range

struct <T> Range

A bounded range: a..b (exclusive end) and a..=b (inclusive end).

Field order is evaluation order: RangeLowering builds a range as a designated initializer, and C++ evaluates those in declaration order, so f()..g() runs f first. Keep begin before end. A for loop over a range is lowered to a counting loop directly and never builds one.

Example

fn main() -> i32 {
    var sum = 0
    for i in 0..4 { sum += i }
    return sum - 6
}

RangeFrom

struct <T> RangeFrom

A range with no end: a.., or .. as begin: 0 (a RangeFrom<usize>).

Only valid as a subscript index, such as v[2..].

RangeTo

struct <T> RangeTo

A range with no start: ..b or ..=b.

Only valid as a subscript index, such as v[..3].

Generated from Kairo source, Apache-2.0 WITH AdditionRef-Kairo-Runtime-exception.