rust-lang / rust-lang/rust-clippy

needless_borrow emitted on expression that changes types when `&` is removed

Open
#14,352 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

C-bug I-false-positive I-suggestion-causes-error
Dominant language
Rust
Stars
13.5k
Forks
2.2k
Avg merge
2d 10h
Merged PRs (30d)
32

Description

Summary

The error after clippy --fix, this should compile in my opinion. It does compile without the curly braces around guard. It is not a clippy false positive if this is considered a rustc bug.

error[E0308]: mismatched types
 --> src/main.rs:6:17
  |
6 |     function(&{ guard });
  |                 ^^^^^ expected `()`, found `Ref<'_, ()>`
  |
  = note: expected unit type `()`
                found struct `std::cell::Ref<'_, ()>`
Lint Name

needless_borrow

Reproducer

I tried this code:

fn function(_: &()) {}

fn main() {
    let refcell = core::cell::RefCell::new(());
    let guard = refcell.borrow();
    function(&&{ guard }); // two &
}

I saw this happen:

"failed to automatically apply fixes suggested by rustc"

I expected to see this happen:

I expected the result after clippy --fix to compile

fn function(_: &()) {}

fn main() {
    let refcell = core::cell::RefCell::new(());
    let guard = refcell.borrow();
    function(&{ guard }); // one &
}
Version
rustc 1.85.0 (4d91de4e4 2025-02-17)
binary: rustc
commit-hash: 4d91de4e48198da2e33413efdcd9cd2cc0c46688
commit-date: 2025-02-17
host: x86_64-unknown-linux-gnu
release: 1.85.0
LLVM version: 19.1.7
Additional Labels

@rustbot label I-suggestion-causes-error

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by running the supplied Rust reproducer with the needless_borrow lint and clippy --fix, then inspect the lint's fix suggestion and the resulting type error. Done means the suggested fix no longer changes the expression's type unexpectedly and the fixed reproducer compiles, or the issue is confirmed to be a rustc problem.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
tooling
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.