I'm new to Rust, but I think I understand the concept of lifetime parameters well enough. I can see how this would be really useful for methods, when accepting multiple parameters by reference. However, I can't think of an example when a struct would hold references to two different variables with different lifetimes. The Rust book doesn't provide an example of a struct with multiple lifetimes.
The discussion around Elision 2.0 refers to "structs with a single lifetime parameter", and is focused on making it easier to work with types that have only one lifetime parameter, which suggests to me that this is the most common use case for lifetimes - either a struct has no lifetime, or it has one lifetime.
Can anyone provide me with a practical example of a struct with multiple lifetime parameters?
When you use a reference in a struct, you use a lifetime.
Sometimes you can just use the same lifetime for the various references of your struct, but you can't always do that.
A lifetime is a reference to the time a value is alive (between creation and deletion). And it's a constraint that the borrow checker will check. If you give the same lifetime to two fields, you add a constraint that often can't be verified, thus limiting the possible uses of your struct.
Here's a real world example:
pub struct DisplayableLine<'s, 'l, 'p> {
pub skin: &'s MadSkin,
pub line: &'p FmtLine<'l>,
pub width: Option<usize>, // available width
}
The struct itself is usually short lived. The skin and the line come from different origins. You could have a skin you just make for a display and that you want to immediately drop. Or a line you just made while you keep your skin around. Giving the same lifetime to both fields would be more limiting than necessary.
Of course when your struct is always referring to values that are created together and dropped together, having two lifetimes isn't necessary. But in practice this is rare.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With