How to create enum with lifetime?

I am learning Rust and currently looking at Smart Pointer in 'The Rust Programming Language' book.

I am on the part..

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.

So trying to create lifetime for the enum as below, but am getting error. Is it impossible for self reference lifetime? or something illogical with the code below?

enum List<'a> {
    Cons(i32, Box<&'a List>),
    Nil
}

playground link

You need to use Box<&'a List<'a>> instead of Box<&'a List> (notice how List has an explicit 'a).

Also, if you're already storing a reference (&List) you can skip the Box to avoid a second layer of indirection.

enum List<'a> {
    Cons(i32, &'a List<'a>),
    Nil,
}

Also, a frequently recommended resource on implementing linked lists in Rust is Learn Rust With Entirely Too Many Linked Lists. I'd recommend checking it out once you're feeling more confident with the language, it goes through how you can implement a linked list, starting from the simplest implementation and working towards the unsafe version you are typically taught when learning C.

1 Like

Thanks for sharing on Learn Rust With Entirely Too Many Linked Lists. It looks like a good way to internalize various Rust knowledge!

1 Like

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