HiveBrain v1.2.0
Get Started
← Back to all entries
patternrustMajor

When is it useful to define multiple lifetimes in a struct?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
structusefullifetimesmultiplewhendefine

Problem

In Rust, when we want a struct to contain references, we typically define their lifetimes as such:

struct Foo {
    x: &'a i32,
    y: &'a i32,
}


But it's also possible to define multiple lifetimes for different references in the same struct:

struct Foo {
    x: &'a i32,
    y: &'b i32,
}


When is it ever useful to do this? Can someone provide some example code that doesn't compile when both lifetimes are 'a but does compile when the lifetimes are 'a and 'b (or vice versa)?

Solution

After staying up way too late, I was able to come up with an example case where the lifetimes matter. Here is the code:

static ZERO: i32 = 0;

struct Foo {
x: &'a i32,
y: &'b i32,
}

fn get_x_or_zero_ref(x: &'a i32, y: &'b i32) -> &'a i32 {
if x > y {
return x
} else {
return &ZERO
}
}

fn main() {
let x = 1;
let v;
{
let y = 2;
let f = Foo { x: &x, y: &y };
v = get_x_or_zero_ref(&f.x, &f.y);
}
println!("{}", *v);
}


If you were to change the definition of Foo to this:

struct Foo {
x: &'a i32,
y: &'a i32,
}


Then the code won't compile.

Basically, if you want to use the fields of the struct on any function that requires it's parameters to have different lifetimes, then the fields of the struct must have different lifetimes as well.

Context

Stack Overflow Q#29861388, score: 50

Revisions (0)

No revisions yet.