Trying to understand Rust through the "Rust Programming Language" book, I got to a point where I have another (begginer) question.
In chapter 15, section 15.4 ("Rc, the Reference Counted Smart Pointer") the author first try to implement a shared ownership Cons list without the Rc pointer with the following code:
enum List {
Cons(i32, Box<List>),
Nil,
}
use crate::List::{Cons, Nil};
fn main() {
let a = Cons(5, Box::new(Cons(10, Box::new(Nil))));
let b = Cons(3, Box::new(a));
let c = Cons(4, Box::new(a));
}
Which yields to a compiler error due to the move of variable "a".
To which he/she states:
We could change the definition of Cons to hold references instead, but then we would have to specify lifetime parameters. By specifying lifetime parameters, we would be specifying that every element in the list will live at least as long as the entire list. The borrow checker wouldn’t let us compile let a = Cons(10, &Nil); for example, because the temporary Nil value would be dropped before a could take a reference to it.
Not fully undertanding what he/she meant by The borrow checker wouldn’t let us compile let a = Cons(10, &Nil); for example, because the temporary Nil value would be dropped before a could take a reference to it.
, I tried to implement it myself:
use crate::List::{Cons, Nil};
#[derive(Debug)]
enum List<'a> {
Cons(i32, &'a List<'a>),
Nil,
}
fn main() {
let test = Cons(10, &Nil);
println!("test: {:?}", test);
let a = Cons(3, &Cons(2, &Cons(1, &Nil)));
let b = Cons(4, &a);
let c = Cons(5, &a);
println!("a: {:?}", a);
println!("b: {:?}", b);
println!("c: {:?}", c);
}
Which I successfully compiled and got the following output:
test: Cons(10, Nil)
a: Cons(3, Cons(2, Cons(1, Nil)))
b: Cons(4, Cons(3, Cons(2, Cons(1, Nil))))
c: Cons(5, Cons(3, Cons(2, Cons(1, Nil))))
So what did the author mean by
The borrow checker wouldn’t let us compile let a = Cons(10, &Nil); for example, because the temporary Nil value would be dropped before a could take a reference to it.
?