Skip to content

Inconsistent borrow check in async function #74068

Description

@Nugine

I tried this code:

use std::collections::HashMap;

fn f1(map: &mut HashMap<i32, String>, k: i32) -> &String {
    if let Some(s) = map.get(&k) {
        return s;
    }
    map.insert(k, k.to_string());
    map.get(&k).unwrap()
}

async fn f2(map: &mut HashMap<i32, String>, k: i32) -> &String {
    if let Some(s) = map.get(&k) {
        return s;
    }
    map.insert(k, k.to_string());
    map.get(&k).unwrap()
}

f2 seems to be correct but can not be compiled.

   Compiling playground v0.0.1 (/playground)
error[E0502]: cannot borrow `*map` as mutable because it is also borrowed as immutable
  --> src/lib.rs:15:5
   |
12 |     if let Some(s) = map.get(&k) {
   |                      --- immutable borrow occurs here
13 |         return s;
   |                - returning this value requires that `*map` is borrowed for `'1`
14 |     }
15 |     map.insert(k, k.to_string());
   |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here
16 |     map.get(&k).unwrap()
17 | }
   | - return type of generator is &'1 std::string::String

error: aborting due to previous error

For more information about this error, try `rustc --explain E0502`.
error: could not compile `playground`.

To learn more, run the command again with --verbose.

Meta

According to the playground, the problem exists on 1.44.1 and 1.46.0-nightly (2020-07-04 0cd7ff7ddfb75a38dca8).

Other versions may be the same.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-borrow-checkerArea: The borrow checkerC-bugCategory: This is a bug.NLL-poloniusIssues related for using Polonius in the borrow checkerP-mediumMedium priorityT-compilerRelevant to the compiler team, which will review and decide on the PR/issue.fixed-by-poloniusCompiling with `-Zpolonius` fixes this issue.

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions