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. }
  6. // `<'a: 'b, 'b>` reads as lifetime `'a` is at least as long as `'b`.
  7. // Here, we take in an `&'a i32` and return a `&'b i32` as a result of coercion.
  8. fn choose_first<'a: 'b, 'b>(first: &'a i32, _: &'b i32) -> &'b i32 {
  9. first
  10. }
  11. fn main() {
  12. let first = 2; // Longer lifetime
  13. {
  14. let second = 3; // Shorter lifetime
  15. println!("The product is {}", multiply(&first, &second));
  16. println!("{} is the first", choose_first(&first, &second));
  17. };
  18. }