Common conversion and comparison traits
Quick answer
Rust uses standard traits for common conversions and comparisons. Prefer them when designing interoperable types rather than inventing unrelated conversion methods.
Choose conversion contracts
From expresses an infallible conversion; implementing From also provides the corresponding Into conversion through a blanket implementation. TryFrom returns Result when conversion may fail. PartialEq supports equality; Eq promises a stronger equivalence relation, and Ord requires a consistent total order.
fn main() { let small: u8 = 250; let large: u16 = u16::from(small); println!("{large}");}Expected stdout (not executed):
250Every u8 can fit in u16.
fn main() { println!("fits: {}", u8::try_from(300u16).is_ok()); println!("comparison: {}", 3.cmp(&8) == std::cmp::Ordering::Less);}Expected stdout (not executed):
fits: falsecomparison: trueTryFrom preserves failure; cmp describes the ordering.
Common mistake
Do not use as for checked narrowing; it may truncate instead of returning an error.
Try it yourself
Test conversions of 255 and 256 from u16 to u8, then explain the difference.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Common conversion and comparison traits — practice quiz
Choose one answer per question, then review the explanation.
If a type implements `From<u16>` for a local Wrapper, what corresponding conversion is provided?
Which conversion is appropriate for narrowing 300u16 to u8 with failure reporting?
What additional promise does Eq make beyond PartialEq?