Closed
Description
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