Stream: t-compiler

Topic: Order of lifetime declarations matters?


Jake Goulding (Apr 24 2019 at 00:44, on Zulip):

This code compiles:

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

impl<'c, 's> Parser<'c, 's> {
    fn parse(&self) -> &'s str {
        self.context
    }
}

fn parse_context<'s>(context: &'s str) -> &'s str {
    Parser { context: &context }.parse()
}

fn main() {
    parse_context("Available?");
}

If you swap the declaration order of the lifetimes, it breaks:

struct Parser<'s, 'c> {
error[E0515]: cannot return value referencing function parameter `context`
  --> src/main.rs:12:5
   |
12 |     Parser { context: &context }.parse()
   |     ^^^^^^^^^^^^^^^^^^--------^^^^^^^^^^
   |     |                 |
   |     |                 `context` is borrowed here
   |     returns a value referencing data owned by the current function

That's got to be a straight-up bug, yeah?

simulacrum (Apr 24 2019 at 00:46, on Zulip):

I think so, yes. Probably worth filing an issue.

Jake Goulding (Apr 24 2019 at 01:20, on Zulip):

Thanks! https://github.com/rust-lang/rust/issues/60219

Jake Goulding (Apr 24 2019 at 11:05, on Zulip):

@simulacrum I'm not following @Esteban K├╝ber's explanation; can you help me bridge the gap?

Jake Goulding (Apr 24 2019 at 11:06, on Zulip):

Is it that it's effectively become

impl<'c, 's> Parser<'s, 'c> {
// .                ^^^^^^ flipped
    fn parse(&self) -> &'s str {
// .                    ^^ now the shorter lifetime
davidtwco (Apr 24 2019 at 11:09, on Zulip):

That aligns with my understanding of the comment.

Jake Goulding (Apr 24 2019 at 11:26, on Zulip):

Thank you!

Last update: Nov 16 2019 at 02:30UTC