Help message for lifetime parameter

I have this in main.rs:

struct Element {
    Head: i64,
    Tail: &Element
}

fn main() {
    println!("Hello, world!");
}

when I ran cargo run i got:

error[E0106]: missing lifetime specifier
 --> src/main.rs:3:11
  |
3 |     Tail: &Element
  |           ^ expected named lifetime parameter
  |
help: consider introducing a named lifetime parameter
  |
1 | struct Element<'a> {
2 |     Head: i64,
3 |     Tail: &'a Element
  |

I then changed it to what was suggested and ran cargo run again and i got:

error[E0106]: missing lifetime specifier
 --> src/main.rs:3:15
  |
3 |     Tail: &'a Element
  |               ^^^^^^^ expected named lifetime parameter
  |
help: consider using the `'a` lifetime
  |
3 |     Tail: &'a Element<'a>
  |               ^^^^^^^^^^^

So i made the change; and it compiled and printed the line. (along with some warnings)

My question is, what caused it to produce help message in this two steps? Instead of proving the full fix at the first time.

rustc 1.51.0

Well, it must just have been that the people who wrote the code behind it didn't think of this particular case.

Fwiw you almost certainly want this:

struct Element {
    head: i64,
    tail: Box<Element>,
}

Using references (&) in struct fields is tricky and usually not what you want, especially in the context of recursive types. An owning pointer like Box will be exactly as efficient, but won't get you in trouble with the borrow check. (Also as written you can never soundly construct a value of this type since it would require infinite memory, so probably Option<Box<Element>> is the right type for tail.)

I do think it would be good if the compiler avoided suggesting &'a Element<'a> (with the same lifetime on both Element and the outer borrow) since this is almost never a useful type.

3 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.