Skip to content

Lifetimes: Shouldn't the compiler figure out and prolong lifetimes of temporary values where it makes sense? #49118

Closed
@axos88

Description

@axos88

Reading the book currently, and could not really grasp why it's not possible to create a cons list without Box<>, so I tried it...

The results were... not satisfactory for me... Shouldn't the compiler be smart enough and prolong the lifetimes of the temporary values in case of "error"? Or is that a not-as-easy-as-it-sounds problem?

I'm pretty sure there are other real-life scenarios where I wouldn't want to name all the intermediary values...

Btw, shouldn't the first case fail to compile as well, since the lifetime of the shadowed variable is supposed to end when it gets shadowed, doesn't it?

enum List<'a, T: Copy + 'a> {
    Nil,
    Con(T, &'a List<'a, T>)
}

impl<'a, T: Copy + 'a> List<'a, T> {
    fn push(&'a self, value: T ) -> List<'a, T> {
        List::Con(value, self)
    }
}


fn main() {
    let works = List::Nil;
    let works = works.push(7);
    let works = works.push(5);
    let works = works.push(3);

    // temporary value does not live long enough
    let error = List::Nil
        .push(7)
        .push(5)
        .push(3);
}

error[E0597]: borrowed value does not live long enough
  --> src/main.rs:19:17
   |
19 |       let error = List::Nil
   |  _________________^
20 | |         .push(7)
21 | |         .push(5)
   | |________________^ temporary value does not live long enough
22 |           .push(3);
   |                   - temporary value dropped here while still borrowed
23 |   }
   |   - temporary value needs to live until here
   |
   = note: consider using a `let` binding to increase its lifetime

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-NLLArea: Non-lexical lifetimes (NLL)C-enhancementCategory: An issue proposing an enhancement or a PR with one.T-langRelevant to the language 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