Structs

Annotation of lifetimes in structures are also similar to functions:

  1. // A type `Borrowed` which houses a reference to an
  2. // `i32`. The reference to `i32` must outlive `Borrowed`.
  3. #[derive(Debug)]
  4. struct Borrowed<'a>(&'a i32);
  5. // Similarly, both references here must outlive this structure.
  6. #[derive(Debug)]
  7. struct NamedBorrowed<'a> {
  8. x: &'a i32,
  9. y: &'a i32,
  10. }
  11. // An enum which is either an `i32` or a reference to one.
  12. #[derive(Debug)]
  13. enum Either<'a> {
  14. Num(i32),
  15. Ref(&'a i32),
  16. }
  17. fn main() {
  18. let x = 18;
  19. let y = 15;
  20. let single = Borrowed(&x);
  21. let double = NamedBorrowed { x: &x, y: &y };
  22. let reference = Either::Ref(&x);
  23. let number = Either::Num(y);
  24. println!("x is borrowed in {:?}", single);
  25. println!("x and y are borrowed in {:?}", double);
  26. println!("x is borrowed in {:?}", reference);
  27. println!("y is *not* borrowed in {:?}", number);
  28. }

See also:

structs