-
Notifications
You must be signed in to change notification settings - Fork 13.9k
Description
Imagine you have a u32. You want to check if it's larger than the maximum value of a u16. Of course, you know that the API will give you a u16, so you will need to cast it to a u32.
You write a unit test. 100 million should be above the range of a u16, you think.
let x = 100_000_000;
let y = u16::max as u32;
println!("{}", x > y);Output:
false
You begin to doubt your computer science education. In a fugue, you abandon all worldly possessions. You move to the woods. You raise chickens now; sometimes, though, you wonder if they're truly the ones raising you. It is a simpler life.
u16::max is the UFCS'd form of the default'd max method on the prelude'd Ord trait. To a first approximation, there is no reason to ever directly cast a function item to anything other than a usize. The compiler should emit a warning when attempting to cast a function item to u8, u16, u32, u64, u128, i8, i16, i32, i64, i128, and isize. This would not apply to transitive casts; foo as usize as i8 would not warn.
(If I had realized this existed, I would have renamed u16::MAX back when I had the chance.)