Functions

Ignoring elision, function signatures with lifetimes have a few constraints:

  • any reference must have an annotated lifetime.
  • any reference being returned must have the same lifetime as an input or
    be static.

Additionally, note that returning references without input is banned if it
would result in returning references to invalid data. The following example shows
off some valid forms of functions with lifetimes:

  1. // One input reference with lifetime `'a` which must live
  2. // at least as long as the function.
  3. fn print_one<'a>(x: &'a i32) {
  4. println!("`print_one`: x is {}", x);
  5. }
  6. // Mutable references are possible with lifetimes as well.
  7. fn add_one<'a>(x: &'a mut i32) {
  8. *x += 1;
  9. }
  10. // Multiple elements with different lifetimes. In this case, it
  11. // would be fine for both to have the same lifetime `'a`, but
  12. // in more complex cases, different lifetimes may be required.
  13. fn print_multi<'a, 'b>(x: &'a i32, y: &'b i32) {
  14. println!("`print_multi`: x is {}, y is {}", x, y);
  15. }
  16. // Returning references that have been passed in is acceptable.
  17. // However, the correct lifetime must be returned.
  18. fn pass_x<'a, 'b>(x: &'a i32, _: &'b i32) -> &'a i32 { x }
  19. //fn invalid_output<'a>() -> &'a String { &String::from("foo") }
  20. // The above is invalid: `'a` must live longer than the function.
  21. // Here, `&String::from("foo")` would create a `String`, followed by a
  22. // reference. Then the data is dropped upon exiting the scope, leaving
  23. // a reference to invalid data to be returned.
  24. fn main() {
  25. let x = 7;
  26. let y = 9;
  27. print_one(&x);
  28. print_multi(&x, &y);
  29. let z = pass_x(&x, &y);
  30. print_one(z);
  31. let mut t = 3;
  32. add_one(&mut t);
  33. print_one(&t);
  34. }

See also:

functions