Skip to content

unnecessary_cast false positive when casting pointers to types with lifetime parameters #12860

Open
@ia0

Description

@ia0

Summary

unnecessary-lint suggests x as *const T instead of x as *const T as *const S where both casts are actually needed, otherwise the code doesn't compile.

Lint Name

unnecessary-cast

Reproducer

I tried this code:

pub struct Foo<'a>(pub &'a [u8]);

/// # Safety
pub unsafe fn foo<'a, 'b>(x: &'a Foo<'a>) -> &'b Foo<'b> {
    unsafe { &*(x as *const Foo<'a> as *const Foo<'b>) }
}

I saw this happen:

warning: casting raw pointers to the same type and constness is unnecessary (`*const Foo<'_>` -> `*const Foo<'_>`)
 --> src/lib.rs:5:16
  |
5 |     unsafe { &*(x as *const Foo<'a> as *const Foo<'b>) }
  |                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `x as *const Foo<'a>`
  |
  = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_cast
  = note: `#[warn(clippy::unnecessary_cast)]` on by default

I expected to see this happen: compiles without warning

Version

rustc 1.80.0-nightly (7d83a4c13 2024-05-06)
binary: rustc
commit-hash: 7d83a4c131ab9ae81a74c6fd825c827d74a2881d
commit-date: 2024-05-06
host: x86_64-unknown-linux-gnu
release: 1.80.0-nightly
LLVM version: 18.1.4

Additional Labels

No response

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 have

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions