Card 1 / 12
Swap the values behind two mutable references. &mut T lets you modify a value without taking ownership, and *a dereferences the reference to reach the value itself.
a |
b |
a after the call |
b after the call |
|---|---|---|---|
5 |
10 |
10 |
5 |
7 |
7 |
7 |
7 |
Store *a in a temp variable, assign *b into *a, then assign the temp into *b. As an alternative, the standard library does this in one call: std::mem::swap(a, b) exchanges the values behind two &mut references.
/// Swap two values using mutable references
fn swap(a: &mut i32, b: &mut i32) {
let temp = *a;
*a = *b;
*b = temp;
}Card 2 / 12
Double every element of the slice in place. iter_mut() yields mutable references to the elements, and *x *= 2 dereferences and multiplies in one step.