Lifetimes

Every variable, structure attribute, and constant has a lifetime in Rust. Most of them can be elided, since we usually know that a constant has a static lifetime (it will always be there for us), or that most of the variables have the lifetime of its scope. Nevertheless, there is sometimes a place where we need to specify that lifetime. Let's check the following structures:

struct Parent<'p> {    age: u8,    child: Option<&'p Child>,}struct Child {    age: u8,}

As you can see, the parent has a reference to the child, but we added two letters preceded by a single quote. These are lifetime specifications, and what means is that the reference to the child has to live at least while the parent exists. Let's see this behavior with a simple

Get Rust High Performance now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.