Search code examples
structrustenumslifetime

Enum variant that references a struct


I am new to rust. I have this code:

enum Foo {
    F1 { x: Vec<Foo>, y: i32 },
    F2 { x: &Bar },
}

struct Bar {
    x: i32,
    y: Vec<Foo>,
}

Obviously, this won't compile, because I have to give a lifetime param, which leads to this:

enum Foo<'a> {
    F1 { x: Vec<Foo<'a>>, y: i32 },
    F2 { x: &'a Bar<'a> },
}

struct Bar<'a> {
    x: i32,
    y: Vec<Foo<'a>>,
}

Is using lifetimes like this good practice? In this case, I need F2 to have a reference to Bar.


Solution

  • The lifetime annotations you have written are appropriate for this situation. (There are other cases where it might be preferable to use multiple lifetime parameters, such as when dealing with &mut references, to avoid over-constraining lifetimes, but this is not such a case.)

    However, it might be that you actually don't want to use a &Bar at all, but some other type such as Box<Bar> or Rc<Bar> that owns the Bar struct. In that case, you won't need the lifetime annotations. Whether this is that case depends on how these structures are constructed and used, so it can't be determined from just the type declarations — but you'll find out via compile errors when you try to use them, if so.