pointers/ref
For pointers, a distinction needs to be made between destructuring
and dereferencing as they are different concepts which are used
differently from a language like C.
- Dereferencing uses
* - Destructuring uses
&,ref, andref mut
1. fn main() {
2. // Assign a reference of type `i32`. The `&` signifies there
3. // is a reference being assigned.
4. let reference = &4;
6. match reference {
7. // If `reference`s is pattern matched against `&val`, it results
8. // in a comparison like:
9. // `&i32`
10. // `&val`
11. // ^ We see that if the matching `&`s are dropped, then the `i32`
12. // should be assigned to `val`.
13. &val => println!("Got a value via destructuring: {:?}", val),
14. }
16. // To avoid the `&`, you dereference before matching.
17. match *reference {
18. val => println!("Got a value via dereferencing: {:?}", val),
19. }
21. // What if you don't start with a reference? `reference` was a `&`
22. // because the right side was already a reference. This is not
23. // a reference because the right side is not one.
24. let _not_a_reference = 3;
26. // Rust provides `ref` for exactly this purpose. It modifies the
27. // assignment so that a reference is created for the element; this
28. // reference is assigned.
29. let ref _is_a_reference = 3;
31. // Accordingly, by defining 2 values without references, references
32. // can be retrieved via `ref` and `ref mut`.
33. let value = 5;
34. let mut mut_value = 6;
36. // Use `ref` keyword to create a reference.
37. match value {
38. ref r => println!("Got a reference to a value: {:?}", r),
39. }
41. // Use `ref mut` similarly.
42. match mut_value {
43. ref mut m => {
44. // Got a reference. Gotta dereference it before we can
45. // add anything to it.
46. *m += 10;
47. println!("We added 10. `mut_value`: {:?}", m);
48. },
49. }
50. }
