Lifetime parameters are not prescriptive

  • Don’t prescribe how long an input reference or value actually lives
  • Don’t change how long an input reference or value actually lives
  • Can’t use lifetime parameters to set/assign/force a lifetime
  • Can’t make a reference live long enough
  1. fn return_first_two() -> &[i32] {
  2. let list = vec![1,2,3,4,5];
  3. &list[0..2]
  4. }

this will not compile as list does not outlive the lifetime of function
image.png
even if we add lifetime parameter to function to force this to compile

  1. fn return_first_two<'a>() -> &'a [i32] {
  2. let list = vec![1,2,3,4,5];
  3. &list[0..2]
  4. }

image.png
still doesn’t compile

use static

  1. static LIST:[i32;4] = [1,2,3,4];
  2. fn return_first_two_with_static() -> &'static [i32] {
  3. &LIST[0..2]
  4. }

HRTB

  1. trait Trait<T> {
  2. fn do_sth(&self, value: T);
  3. }
  4. fn foo<'a>(a: &'a usize, b: &dyn Trait<&'a usize>) {
  5. let x: usize = 10;
  6. b.do_sth(a);
  7. }
  8. fn bar(b: &dyn for<'a> Trait<&'a usize>) {
  9. let x: usize = 10;
  10. b.do_sth(&x);
  11. }

How does for<> syntax differ from a regular lifetime bound?
Higher-Rank Trait Bounds

Lifetime parameters are descriptive

  • Describe intended relationships between references
  • Concrete lifetimes that fill in the parameters are determined by the code calling the definitions containing lifetime parameters

Fixing Lifetime errors

ask questions

  • what are the relationships in the implementation?
  • what are the concrete lifetimes where the definition is used
  • how do I reorganize the code so the references are always valid?
  • would owned values be more approprited than references?