Skip to content

Spurious "borrowed value does not live long enough" when calling a function through a function pointer #49073

Closed
@glandium

Description

@glandium

The following code (edited to an even smaller version provided by occultus):

use std::string::ToString;

fn main() {
    let to_string = ToString::to_string;
    let i = 1;
    let b = &i;
    assert_eq!("", to_string(&b));
}

yields the following compiler output:

error[E0597]: `i` does not live long enough
 --> src/main.rs:6:14
  |
6 |     let b = &i;
  |              ^ borrowed value does not live long enough
7 |     assert_eq!("", to_string(&b));
8 | }
  | - `i` dropped here while still borrowed
  |
  = note: values in a scope are dropped in the opposite order they are created

Moving let to_string down one line "fixes" it. So does #![feature(nll)].

In case you wonder how one ends up with code like this, it's because this is test code, and to_string is actually <Trait as ToString>::to_string, which is a lot of boilerplate.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-borrow-checkerArea: The borrow checkerC-enhancementCategory: An issue proposing an enhancement or a PR with one.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.fixed-by-NLLBugs fixed, but only when NLL is enabled.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions