I'm learning Rust from the official book. Concerning Rc, it has the following section:
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 compilelet a = Cons(10, &Nil);
for example, because the temporaryNil
value would be dropped beforea
could take a reference to it.
I implement this with the following code, and it can compile and run:
#[derive(Debug)]
enum List2<'a> {
Cons(i32, &'a List2<'a>),
Nil,
}
use crate::List2::{Cons, Nil};
fn main() {
let x = Cons(1, &Nil);
let y = Cons(2, &x);
let z = Cons(3, &x);
println!("{:?}", y);
println!("{:?}", z);
}
result:
Cons(2, Cons(1, Nil))
Cons(3, Cons(1, Nil))
Is my implementation has some problems or the official docs is out of date?