• ref 模式

    ref 模式

    在通过 let 绑定来进行模式匹配或解构时,ref 关键字可用来接受结构体/元组的字段的引用。下面的例子展示了几个实例,可看到 ref 的作用:

    1. #[derive(Clone, Copy)]
    2. struct Point { x: i32, y: i32 }
    3. fn main() {
    4. let c = 'Q';
    5. // 赋值语句中左边的 `ref` 关键字等价右边的 `&` 符号。
    6. let ref ref_c1 = c;
    7. let ref_c2 = &c;
    8. println!("ref_c1 equals ref_c2: {}", *ref_c1 == *ref_c2);
    9. let point = Point { x: 0, y: 0 };
    10. // 在解构一个结构体时 `ref` 同样有效。
    11. let _copy_of_x = {
    12. // `ref_to_x` 是一个指向 `point` 的 `x` 字段的引用。
    13. let Point { x: ref ref_to_x, y: _ } = point;
    14. // 返回一个 `point` 的 `x` 字段的拷贝。
    15. *ref_to_x
    16. };
    17. // `point` 的可变拷贝
    18. let mut mutable_point = point;
    19. {
    20. // `ref` 可以结合 `mut` 来接受可变引用。
    21. let Point { x: _, y: ref mut mut_ref_to_y } = mutable_point;
    22. // 通过可变引用来改变 `mutable_point` 的字段 `y`。
    23. *mut_ref_to_y = 1;
    24. }
    25. println!("point is ({}, {})", point.x, point.y);
    26. println!("mutable_point is ({}, {})", mutable_point.x, mutable_point.y);
    27. // 包含一个指针的可变元组
    28. let mut mutable_tuple = (Box::new(5u32), 3u32);
    29. {
    30. // 解构 `mutable_tuple` 来改变 `last` 的值。
    31. let (_, ref mut last) = mutable_tuple;
    32. *last = 2u32;
    33. }
    34. println!("tuple is {:?}", mutable_tuple);
    35. }