指针和引用

对指针来说,解构(destructuring)和解引用(dereferencing)要区分开, 因为这两者的概念是不同的,和 C 那样的语言用法不一样。

  • 解引用使用 *
  • 解构使用 &,ref, 和 ref mut
1. fn main() {
2. // 获得一个 `i32` 类型的引用。`&` 表示获取一个引用。
3. let reference = &4;

5. match reference {
6. // 如果 `reference` 是对 `&val` 进行模式匹配,则会产生如下比较行为:
7. // `&i32`
8. // `&val`
9. // ^ 我们看到,如果匹配的 `&` 都去掉了,那么就是 `i32` 赋给 `val`。
10. &val => println!("Got a value via destructuring: {:?}", val),
11. }

13. // 为了避免 `&` 的使用,需要在匹配前解引用。
14. match *reference {
15. val => println!("Got a value via dereferencing: {:?}", val),
16. }

18. // 如果没有一个引用头部(以 & 开头)会是怎样? `reference` 是一个 `&`,
19. // 因为右边已经是一个引用。
20. // 下面这个不是引用,因为右边不是。
21. let _not_a_reference = 3;

23. // Rust 对这种情况提供了 `ref`。它更改了赋值行为,使得可以对具体值
24. // 创建引用。这将得到一个引用。
25. let ref _is_a_reference = 3;

27. // 相应地,定义两个非引用的值,通过 `ref` 和 `mut` 可以取得引用。
28. let value = 5;
29. let mut mut_value = 6;

31. // 使用 `ref` 关键字来创建引用。
32. match value {
33. ref r => println!("Got a reference to a value: {:?}", r),
34. }

36. // 类似地使用 `ref mut`。
37. match mut_value {
38. ref mut m => {
39. // 获得一个引用。在增加内容之前,要先得到解引用(Gotta
40. // dereference it before we can add anything to it)。
41. *m += 10;
42. println!("We added 10. `mut_value`: {:?}", m);
43. },
44. }
45. }