< (less-than) operator is a binary comparison operator that evaluates whether the left-hand operand is strictly less than the right-hand operand, returning a bool.
At the compiler level, the < operator is syntactic sugar for the lt method provided by the std::cmp::PartialOrd trait.
Trait Implementation
To use the< operator with a specific type, that type must implement PartialOrd. Because PartialOrd has a supertrait bound on PartialEq, any type supporting < must also support the == operator.
Evaluation Mechanics
- Delegation to
partial_cmp: The default implementation ofltcallspartial_cmp, which returns anOption<std::cmp::Ordering>. - Strict Evaluation: The
<operator evaluates totrueonly ifpartial_cmpreturnsSome(Ordering::Less). - Incomparable Values: If
partial_cmpreturnsNone(which occurs with incomparable values, such as floating-pointNaN), the<operator evaluates tofalse. - Borrowing: The operator implicitly takes immutable references to both operands (
&selfand&Rhs). It does not consume or move the values being compared.
Type Constraints
Rust enforces strict type safety during comparison. The< operator does not perform implicit type coercion. Both operands must resolve to the same type, or the left-hand type must explicitly implement PartialOrd<Rhs> where Rhs is the type of the right-hand operand.
Derivation
For custom structs and enums, the compiler can automatically generate the< operator logic using #[derive(PartialOrd)]. Because of the supertrait bound, #[derive(PartialEq)] is also strictly required; attempting to derive PartialOrd without deriving PartialEq results in a compilation error.
When derived:
- Structs: Evaluates fields lexicographically, top-to-bottom.
- Enums: Evaluates based on the discriminant (the declared order of variants), followed by lexicographical comparison of any data contained within the variants.
Tired of Poor Rust Skills? Fix That With Deep Grasping!Learn More





