Skip to content

Possible false positive “temporary value dropped while borrowed” error #89265

Open
@EFanZh

Description

@EFanZh

I tried this code:

use std::collections::HashSet;

fn main() {
    let mut set = HashSet::from([("abc", 4)]);

    set.remove(&(String::from("abc").as_str(), 4)); // ERROR: temporary value dropped while borrowed.
    set.remove(&(String::from("abc").as_str(), 4)); // OK.
}

I expected to see this happen: The code compiles successfully.

Instead, this happened: I got the follow error:

error[E0716]: temporary value dropped while borrowed
 --> src/main.rs:6:18
  |
6 |     set.remove(&(String::from("abc").as_str(), 4)); // ERROR: temporary value dropped while borrowed.
  |                  ^^^^^^^^^^^^^^^^^^^              - temporary value is freed at the end of this statement
  |                  |
  |                  creates a temporary which is freed while still in use
7 |     set.remove(&(String::from("abc").as_str(), 4)); // OK.
  |     --- borrow later used here
  |
  = note: consider using a `let` binding to create a longer lived value

For more information about this error, try `rustc --explain E0716`.
error: could not compile `scratch` due to previous error

Meta

rustc --version --verbose:

rustc 1.57.0-nightly (addb4da68 2021-09-25)
binary: rustc
commit-hash: addb4da686a97da46159f0123cb6cdc2ce3d7fdb
commit-date: 2021-09-25
host: x86_64-unknown-linux-gnu
release: 1.57.0-nightly
LLVM version: 13.0.0

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-borrow-checkerArea: The borrow checkerA-diagnosticsArea: Messages for errors, warnings, and lintsA-lifetimesArea: Lifetimes / regionsA-varianceArea: Variance (https://doc.rust-lang.org/nomicon/subtyping.html)D-newcomer-roadblockDiagnostics: Confusing error or lint; hard to understand for new users.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