2

Introduction

I have tried to verify this statement from a chapter of the Rust book about Rc:

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.

Verification of the statement

I have tried to implement and print an enum List. The borrow checker has allowed me to compile and execute it. Although the book describes the opposite behavior.

#[derive(Debug)]
enum List<'a> {
    Cons(i32, &'a List<'a>),
    Nil,
}

use List::{Cons, Nil};

fn main() {
    let a = Cons(5, &Cons(10, &Nil));
    println!("{:?}", a);
}

Then i have separately defined the Nil value. This time, the borrow checker worked as the book described it.

fn main() {
    let n = Nil;
    let a = Cons(5, &Cons(10, &n));
    println!("{:?}", a);
}

Result:

11 |     let a = Cons(5, &Cons(10, &n));
   |                      ^^^^^^^^^^^^ - temporary value dropped here while still borrowed
   |                      |
   |                      temporary value does not live long enough

Questions

1) Why does the borrow checker allow to compile Cons(5, &Cons(10, &Nil))? Is it a mistake in the book?

2) Why does the borrow checker allow to compile Cons(5, &Cons(10, &Nil));, but not Cons(5, &Cons(10, &n));?

3) Why does temporary &Cons(10, &n) would be dropped before next Cons could take a reference to it, but not after an execution process going out of the scope (In my case this scope is the main function)?

Artemij Rodionov
  • 1,721
  • 1
  • 17
  • 22
  • The duplicate applied to this question: `&Cons(10, &Nil)` is promoted to a static lifetime, so it becomes an element of type `List<'static>`. The same promotion is not possible in the second example because of the local variable `n`. – E_net4 Sep 16 '18 at 15:27

0 Answers0