Skip to content

Incorrect suggestion to add a semicolon in if let when trying to borrow a value more than once #85581

Closed
@miDeb

Description

@miDeb

Given the following code: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=ef9ffeffe1ceaef2201ebc972bfc11cd

use std::collections::BinaryHeap;

fn foo(heap: &mut BinaryHeap<i32>) {
    if let Some(value) = heap.peek_mut() {
        heap.pop();
    }
}

The current output is:

error[E0499]: cannot borrow `*heap` as mutable more than once at a time
 --> src/lib.rs:5:9
  |
4 |     if let Some(value) = heap.peek_mut() {
  |                          ---------------
  |                          |
  |                          first mutable borrow occurs here
  |                          a temporary with access to the first borrow is created here ...
5 |         heap.pop();
  |         ^^^^ second mutable borrow occurs here
6 |     }
7 | }
  | - ... and the first borrow might be used here, when that temporary is dropped and runs the destructor for type `Option<PeekMut<'_, i32>>`
  |
help: consider adding semicolon after the expression so its temporaries are dropped sooner, before the local variables declared by the block are dropped
  |
6 |     };
  |      ^

Ideally the output should look like:
Without the "help" part, which is what it looks like when I actually add the semicolon (not sure if the rust compiler could also accept this code without an error)

Metadata

Metadata

Assignees

Labels

A-borrow-checkerArea: The borrow checkerA-diagnosticsArea: Messages for errors, warnings, and lintsA-suggestion-diagnosticsArea: Suggestions generated by the compiler applied by `cargo fix`C-bugCategory: This is a bug.D-invalid-suggestionDiagnostics: A structured suggestion resulting in incorrect code.T-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