Coercion
A longer lifetime can be coerced into a shorter one so that it works inside a scope it normally wouldn’t work in. This comes in the form of inferred coercion by the Rust compiler, and also in the form of declaring a lifetime difference:
1. // Here, Rust infers a lifetime that is as short as possible.
2. // The two references are then coerced to that lifetime.
3. fn multiply<'a>(first: &'a i32, second: &'a i32) -> i32 {
4. first * second
5. }
7. // `<'a: 'b, 'b>` reads as lifetime `'a` is at least as long as `'b`.
8. // Here, we take in an `&'a i32` and return a `&'b i32` as a result of coercion.
9. fn choose_first<'a: 'b, 'b>(first: &'a i32, _: &'b i32) -> &'b i32 {
10. first
11. }
13. fn main() {
14. let first = 2; // Longer lifetime
16. {
17. let second = 3; // Shorter lifetime
19. println!("The product is {}", multiply(&first, &second));
20. println!("{} is the first", choose_first(&first, &second));
21. };
22. }
