There are some syntax missing consistency between book and current rustc(1.34)

In the Rust Programming Book, the section ensuring-one-lifetime-outlives-another-with-lifetime-subtyping of ch19 says:

struct Context<'s>(&'s str);

struct Parser<'c, 's> {
    context: &'c Context<'s>,
}

impl<'c, 's> Parser<'c, 's> {
    fn parse(&self) -> Result<(), &'s str> {
        Err(&self.context.0[1..])
    }
}

fn parse_context(context: Context) -> Result<(), &str> {
    Parser { context: &context }.parse()
}

It should not be compiled, and the error should be like this:

error[E0491]: in type `&'c Context<'s>`, reference has a longer lifetime than the data it references
 --> src/lib.rs:4:5
  |
4 |     context: &'c Context<'s>,
  |     ^^^^^^^^^^^^^^^^^^^^^^^^
  |
note: the pointer is valid for the lifetime 'c as defined on the struct at 3:1
 --> src/lib.rs:3:1
  |
3 | / struct Parser<'c, 's> {
4 | |     context: &'c Context<'s>,
5 | | }
  | |_^
note: but the referenced data is only valid for the lifetime 's as defined on the struct at 3:1
 --> src/lib.rs:3:1
  |
3 | / struct Parser<'c, 's> {
4 | |     context: &'c Context<'s>,
5 | | }
  | |_^

But in rust1.34, it is compiled successfully.

The same happend in following codes:

struct Ref<'a, T>(&'a T);

The book says it sbould not be compiled, and error should be like it:

error[E0309]: the parameter type `T` may not live long enough
 --> src/lib.rs:1:19
  |
1 | struct Ref<'a, T>(&'a T);
  |                   ^^^^^^
  |
  = help: consider adding an explicit lifetime bound `T: 'a`...
note: ...so that the reference type `&'a T` does not outlive the data it points at
 --> src/lib.rs:1:19
  |
1 | struct Ref<'a, T>(&'a T);
  |                   ^^^^^^

But it is ok in rust1.34 too!!.

I think the last one should not be compiled with error. Because the lifetime annotation says the Ref cannot outlive the reference it hold in it’s field T.

These two examples compile thanks to 1.31 new elision rules for example and there is an opened issue for the book, it’s just not done yet.

What the book explains is still valid, it’s just that the compiler will do it for you.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.