Skip to content

unused_allocation lint produces incorrect suggestion for Box comparison #134186

Open
@arvidfm

Description

@arvidfm

Code

pub fn main() {
    let a = Box::new(42);
    println!("{}", a == Box::new(99));
}

Current output

warning: unnecessary allocation, use `&` instead
 --> src/main.rs:3:25
  |
3 |     println!("{}", a == Box::new(99));
  |                         ^^^^^^^^^^^^
  |

Desired output

warning: unnecessary allocation, use `*` instead
 --> src/main.rs:3:25
  |
3 |     println!("{}", *a == 99);
  |                    +
  |

Rationale and extra context

It is invalid to insert & in front of either value (even with deref coercion). The value should be unboxed instead for the comparison to work.

Extra bad because a a == 99 comparison results in an error suggesting wrapping the literal in a Box (see #129083):

error[E0308]: mismatched types
 --> src/main.rs:3:25
  |
3 |     println!("{}", a == 99);
  |                    -    ^^ expected `Box<{integer}>`, found integer
  |                    |
  |                    expected because this is `Box<{integer}>`
  |
  = note: expected struct `Box<{integer}>`
               found type `{integer}`
  = note: for more on the distinction between the stack and the heap, read https://doc.rust-lang.org/book/ch15-01-box.html, https://doc.rust-lang.org/rust-by-example/std/box.html, and https://doc.rust-lang.org/std/boxed/index.html
help: store this in the heap by calling `Box::new`
  |
3 |     println!("{}", a == Box::new(99));
  |                         +++++++++  +

Other cases

Rust Version

rustc 1.83.0 (90b35a623 2024-11-26)
binary: rustc
commit-hash: 90b35a6239c3d8bdabc530a6a0816f7ff89a0aaf
commit-date: 2024-11-26
host: x86_64-unknown-linux-gnu
release: 1.83.0
LLVM version: 19.1.1

Anything else?

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsA-lintsArea: Lints (warnings about flaws in source code) such as unused_mut.D-incorrectDiagnostics: A diagnostic that is giving misleading or incorrect information.L-unused_allocationLint: unused_allocationT-compilerRelevant to the compiler 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