From 3a4d5d4c263161d7cbb23fa7c72ad7c86addbeaf Mon Sep 17 00:00:00 2001 From: Fabian Bornhofen Date: Mon, 9 Jan 2023 17:32:37 +0100 Subject: [PATCH] Add complete code block for lifetimes example --- src/ownership/lifetimes-function-calls.md | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/src/ownership/lifetimes-function-calls.md b/src/ownership/lifetimes-function-calls.md index ec34ae90..98642427 100644 --- a/src/ownership/lifetimes-function-calls.md +++ b/src/ownership/lifetimes-function-calls.md @@ -28,7 +28,27 @@ fn main() { In the above example, try the following: -* Move the declaration of `p2` and `p3` into a a new scope (`{ ... }`). You have to declare `p3` as `let p3: &Point;`, in `main`'s scope before that new block, and in the block assign to `p3` without the `let` (just `p3 = left_most(...)`). Note how this does not compile since `p3` outlives `p2`. +* Move the declaration of `p2` and `p3` into a a new scope (`{ ... }`), resulting in the following code: + ```rust,editable + #[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); + } + ``` + Note how this does not compile since `p3` outlives `p2`. + * Reset the workspace and change the function signature to `fn left_most<'a, 'b>(p1: &'a Point, p2: &'a Point) -> &'b Point`. This will not compile because the relationship between the lifetimes `'a` and `'b` is unclear.