Skip to content

Emit warning when using as to directly cast function items to any integral type other than usize #81686

Open
@bstrie

Description

@bstrie

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.)

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-lintsArea: Lints (warnings about flaws in source code) such as unused_mut.T-langRelevant to the language team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions