Hi rustaceans! I am recently studying rust lifetimes. I devised the following program:
// Program to test complicated lifetime annotations
fn test<'a:'d, 'b:'d+'e,'c:'e, 'd, 'e>(rx: &'a i32, ry:&'b i32, rz: &'c i32)->(&'d i32, &'e i32) {
(if rx<ry {rx} else {ry},
if ry<rz {ry} else {rz})
}
fn main() {
let z:i32 = 3;
let y:i32 = 2;
{
let v: &i32;
{
let x:i32 = 1;
{
let u: &i32;
(u, v) = test(&x, &y, &z);
println!("u={u}");
}
}
println!("v={v}");
}
}
This program compiles and runs fine. The signature of function test is obtained from an experienced rust programmer. Another rust programmer told me to use: fn test(rx: &'a i32, ry:&'a i32, rz: &'a i32)->(&'a i32, &'a i32), which I can understand, but then my main function would not compile. I feel that the all 'a lifetime annotation is too restrictive.
My question is: Although this program compiles successfully, I do not know why. I do not understand the signature of function test. I searched all the books and online materials, but I failed to find any mention of the lifetime annotation syntax used in that signature. Can someone point me to any relevant materials? Thanks!
I was going to link you to the appropriate place in The Book... but I can't find it. @2e71828 found it in the reference, though. The first explanation I could find was this answer on Stack Overflow.
In this specific case, I believe you can explain the annotations for the test function as follows:
'a: 'd: there exists some lifetime 'a which is at least as long-lived as 'd.
'b: 'd+'e: there exists some lifetime 'b which is at least as long-lived as 'd, and at least as long-lived as 'e.
'c: 'e: there exists some lifetime 'c which is at least as long-lived as 'e.
'd: there exists some lifetime 'd.
'e: there exists some lifetime 'e.
This is accounting for the fact that the result lifetimes are a combination of ('a OR 'b, 'b OR 'c).
Another way to think about it: the first tuple position could be either rx or ry. The lifetime of this reference will be called 'd. As such, if you return rx then its lifetime 'a must be at least as long-lived as 'd. Same goes for ry and its lifetime 'b.