Lifetimes in Function Calls
- is a generic parameter, it is inferred by the compiler.
- Lifetimes start with
'
and'a
is a typical default name.
In the above example, try the following:
-
#[derive(Debug)] struct Point(i32, i32); fn left_most<'a>(p1: &'a Point, p2: &'a Point) -> &'a Point { if p1.0 < p2.0 { p1 } else { p2 } } fn main() { let p1: Point = Point(10, 10); let p3: &Point; { let p2: Point = Point(20, 20); p3 = left_most(&p1, &p2); } println!("left-most point: {:?}", p3); }
-
- Two references to two values are borrowed by a function and the function returns another reference.
- Which one is it? The compiler needs to to know, so at the call site the returned reference is not used for longer than a variable from where the reference came from.