rust-lang / rust-lang/rust-clippy

`ref_binding_to_reference` advises to return a reference that doesn't live long enough

Open
#17,370 1 comment 0 reactions 1 assignee View on GitHub

@Gri-ffin is already working on this.

Since Jul 22, 2026.

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

When the ref-d binding is returned from the match:

fn foo(x: String) {
    let _: &&String = match &x {
        ref x => x,
        _ => return,
    };
}

then replacing that with:

fn foo(x: String) {
    let _: &&String = match &x {
        x => &x,
        _ => return,
    };
}

doesn't work, as &x references a local binding x, and thus can't live outside the match.

Lint Name

ref_binding_to_reference

Reproducer

I tried this code:

#![allow(unused)]
#![warn(clippy::ref_binding_to_reference)]

fn foo(x: String) {
    let _: &&String = match &x {
        ref x => x,
        //~^ ref_binding_to_reference
        _ => return,
    };
}

I saw this happen:

warning: this pattern creates a reference to a reference
 --> src/lib.rs:6:9
  |
6 |         ref x => x,
  |         ^^^^^
  |
  = help: for further information visit https://rust-lang.github.io/rust-clippy/rust-1.96.0/index.html#ref_binding_to_reference
note: the lint level is defined here
 --> src/lib.rs:2:9
  |
2 | #![warn(clippy::ref_binding_to_reference)]
  |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
help: try
  |
6 -         ref x => x,
6 +         x => &x,
  |

I expected to see this happen:
no warning, as the result of the fix above:

#![allow(unused)]
#![warn(clippy::ref_binding_to_reference)]

fn foo(x: String) {
    let _: &&String = match &x {
        x => &x,
        //~^ ref_binding_to_reference
        _ => return,
    };
}

doesn't compile:

error[E0597]: `x` does not live long enough
 --> src/lib.rs:6:14
  |
6 |         x => &x,
  |         -    ^-
  |         |    ||
  |         |    |`x` dropped here while still borrowed
  |         |    borrowed value does not live long enough
  |         binding `x` declared here
Version
rustc 1.96.1 (31fca3adb 2026-06-26)
binary: rustc
commit-hash: 31fca3adb283cc9dfd56b49cdee9a96eb9c96ffd
commit-date: 2026-06-26
host: x86_64-unknown-linux-gnu
release: 1.96.1
LLVM version: 22.1.2
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.

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.