70 %
Chris Biscardi

Rust lifetimes for enum variants with structs that have references

Using references in structs in Rust requires specifying lifetimes for those references. In this example I'm writing a Markdown parser so need some enums and structs for references. Markdown headings look something like # this in the ATXHeading version (the SEHeading isn't implemented here and doesn't really matter). So we have a level field for the number of #s and a value that refers to the string of content.

rust
#[derive(Debug, PartialEq, Eq)]
struct ATXHeading<'a> {
level: u8,
value: &'a str,
}
struct SEHeading {}
enum Heading<'a> {
ATXHeading(&'a ATXHeading<'a>),
SEHeading(SEHeading),
}

The lifetime in the ATXHeading makes sure that this string lives long enough for our purposes. We have to place it after the struct name and also in the reference declaration for the string.

rust
struct ATXHeading<'a> {
level: u8,
value: &'a str,
}

To use this struct in the Heading enum, we also have to specify a lifetime that we can then use with the ATXHeading and pass through to the underlying string reference.

rust
enum Heading<'a> {
ATXHeading(&'a ATXHeading<'a>),
SEHeading(SEHeading),
}