Skip to content

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

Closed

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.

Activity

  1. durka commented on Mar 16, 2018

    @durka
    Contributor

    For bonus points, try annotating the type of to_string.

  2. hanna-kruppe commented on Mar 16, 2018

    @hanna-kruppe
    Contributor

    Apparently the code was edited, but the error message was updated to the new code? Very confusing!

  3. glandium commented on Mar 16, 2018

    @glandium
    ContributorAuthor

    Sorry, I forgot to update the line numbers. Fixed.

  4. added
    C-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.
    on Mar 20, 2018
  5. memoryruins commented on Jan 30, 2019

    @memoryruins
    Contributor

    Triage: now compiles on 2018 edition.
    2015 errors:

    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
    

    rustc: 1.32.0

  6. added a commit that references this issue on Mar 11, 2019
    65cb35a
  7. added 3 commits that reference this issue on Apr 22, 2019
    bf0ea60
    c21fbfe
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-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