Hi, I'm Rodo ๐Ÿ‘‹

I'm a Software Engineer

Rodolfo Guluarte Hale

Hi, I'm Rodo ๐Ÿ‘‹

I'm a Software Engineer

Understanding Lifetime Annotations in Struct Definitions in Rust

2 minutes
April 19, 2023

In Rust, the concept of lifetimes ensures that all borrows are valid, preventing references from becoming invalid or pointing to memory that no longer exists. When we define a struct that holds references, we need to specify the lifetime of the reference using lifetime annotations.

Lifetime annotations describe the relationships between the lifetimes of multiple references to ensure that references remain valid for the duration they are used. When a struct holds a reference, it must declare a lifetime parameter, which is the scope for which that reference is valid.

To declare a lifetime parameter for a struct, we use angle brackets and specify the lifetime parameter name. We can then use this lifetime parameter in the struct definition to specify the lifetime of the reference held by the struct.

For example, consider the ImportantExcerpt struct defined as:


struct ImportantExcerpt<'a> {
    part: &'a str,
}

Here, the struct ImportantExcerpt has a single field, part, which is a reference to a string slice. The lifetime parameter ‘a is used to specify that the lifetime of the reference part cannot outlive the lifetime of the struct instance. This annotation means that an instance of ImportantExcerpt canโ€™t outlive the reference it holds in its part field.

When creating an instance of this struct, we need to ensure that the reference passed as an argument to part lives at least as long as the struct instance itself. Otherwise, we would have a reference to invalid memory, leading to a runtime error.

Lifetime annotations ensure that we don’t violate the rules of borrowing and ownership in Rust, enabling us to write safe and correct code.