Skip to content

needless_type_cast is mixing up casts and coercions #16240

@kpreid

Description

@kpreid

Summary

needless_type_cast is in some way mixing up casts and coercions. It is taking my completely-type-annotated code and proposing that I replace the as with a type annotation, which then fails because coercions cannot perform numeric casts.

Lint Name

needless_type_cast

Reproducer

I tried this code:

#![warn(clippy::pedantic)]

pub const fn buffer_size_of<T>() -> u64 {
    let size: usize = size_of::<T>();

    // Ideally this would be `try_into()` but that's not available in const yet.
    // It will never overflow unless 128-bit pointers become a thing.
    let size: u64 = size as u64;
    
    size
}

I saw this happen:

warning: this binding is defined as `usize` but is always cast to `u64`
 --> src/lib.rs:4:15
  |
4 |     let size: usize = size_of::<T>();
  |               ^^^^^ help: consider defining it as: `u64`
  |
  = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#needless_type_cast
  = note: `#[warn(clippy::needless_type_cast)]` implied by `#[warn(clippy::pedantic)]`

Applying the suggestion causes a compilation error since usize does not coerce to u64.

I believe that, instead, the lint should not fire at all in this case.

Version

rustc 1.94.0-nightly (430d8297c 2025-12-13)
binary: rustc
commit-hash: 430d8297c712ca7e8a4866d7ddccf1b71ba5d4d3
commit-date: 2025-12-13
host: aarch64-apple-darwin
release: 1.94.0-nightly
LLVM version: 21.1.5

Additional Labels

@rustbot label +I-suggestion-causes-error

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-bugCategory: Clippy is not doing the correct thingI-false-positiveIssue: The lint was triggered on code it shouldn't haveI-suggestion-causes-errorIssue: The suggestions provided by this Lint cause an ICE/error when applied

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions