• 结构体
    • 参见:

    结构体

    在结构体中标注生命周期也和函数的类似:

    1. // 一个 `Borrowed` 类型,含有一个指向 `i32` 类型的引用。
    2. // 指向 `i32` 的引用必须比 `Borrowed` 寿命更长。
    3. // (原望:A type `Borrowed` which houses a reference to an
    4. // `i32`. The reference to `i32` must outlive `Borrowed`.)
    5. #[derive(Debug)]
    6. struct Borrowed<'a>(&'a i32);
    7. // 和前面类似,这里的两个引用都必须比这个结构体长寿。
    8. #[derive(Debug)]
    9. struct NamedBorrowed<'a> {
    10. x: &'a i32,
    11. y: &'a i32,
    12. }
    13. // 一个枚举类型,不是 `i32` 类型就是一个指向某个量的引用。
    14. //(原文: An enum which is either an `i32` or a reference to one.)
    15. #[derive(Debug)]
    16. enum Either<'a> {
    17. Num(i32),
    18. Ref(&'a i32),
    19. }
    20. fn main() {
    21. let x = 18;
    22. let y = 15;
    23. let single = Borrowed(&x);
    24. let double = NamedBorrowed { x: &x, y: &y };
    25. let reference = Either::Ref(&x);
    26. let number = Either::Num(y);
    27. println!("x is borrowed in {:?}", single);
    28. println!("x and y are borrowed in {:?}", double);
    29. println!("x is borrowed in {:?}", reference);
    30. println!("y is *not* borrowed in {:?}", number);
    31. }

    参见:

    structs