Skip to content

fix suggestion for E0716 (temporary value dropped while borrowed) #137486

Open
@reddevilmidzy

Description

@reddevilmidzy

I tried this code:

fn main() {
    let mut s = String::from("hello");

    let mut ref_s = &mut s;

    ref_s = &mut String::from("world");

    print!("r1 = {}", ref_s);
}

The Rust compiler suggests an incorrect fix:

error[E0716]: temporary value dropped while borrowed
 --> src/main.rs:6:18
  |
6 |     ref_s = &mut String::from("world");
  |                  ^^^^^^^^^^^^^^^^^^^^^- temporary value is freed at the end of this statement
  |                  |
  |                  creates a temporary value which is freed while still in use
7 |
8 |     print!("r1 = {}", ref_s);
  |                       ----- borrow later used here
  |
help: consider using a `let` binding to create a longer lived value
  |
6 ~     let binding = String::from("world");
7 ~     ref_s = &mut binding;
  |

However, this suggestion leads to another compilation error because binding is immutable:

error[E0596]: cannot borrow `binding` as mutable, as it is not declared as mutable
 --> src/main.rs:7:13
  |
7 |     ref_s = &mut binding;
  |             ^^^^^^^^^^^^ cannot borrow as mutable
  |
help: consider changing this to be mutable
  |
6 |     let mut binding = String::from("world");
  |         +++

This forces the user to encounter another error message before arriving at the correct fix.

Expected Fix

The Rust compiler should directly suggest the correct fix:

help: consider using a `let` binding to create a longer lived value
   |
6  ~    let mut binding = String::from("world");
7  ~    ref_s = &mut binding;
   |

This avoids an unnecessary additional compilation error, improving the developer experience.

Meta

rustc --version --verbose:

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

Metadata

Metadata

Assignees

Labels

A-diagnosticsArea: Messages for errors, warnings, and lintsA-suggestion-diagnosticsArea: Suggestions generated by the compiler applied by `cargo fix`D-invalid-suggestionDiagnostics: A structured suggestion resulting in incorrect code.

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions