References
Mutable references
The function std::mem::swap()
takes two mutable references on the same type as parameters and swap them.
Swapping values
Exercise 1.a: Complete the following function (and call it from main()
to see its effect) so that it has the expected effect:
#![allow(unused)] fn main() { fn do_swap() { let mut a = String::from("apple"); let mut b = String::from("bread"); println!("Before swap: a = {a}, b = {b}"); todo!(); // REPLACE ME with something using std::mem::swap() println!("After swap: a = {a}, b = {b}"); } }
The output should look like:
Before swap: a = apple, b = bread
After swap: a = bread, b = apple
You may realize that swapping two String
values do not move the various characters composing the strings in the heap. Only the three fields making up a String
(capacity, pointer, and length) are swapped.
Smallest first
Exercise 1.b: Write a function "smallest_first" with the following prototype which ensures that its first argument is smaller than its second argument and swap them otherwise:
fn smallest_first(a: &mut i32, b: &mut i32) { todo!(); // REPLACE ME } fn main() { let mut a = 42; let mut b = 10; println!("Before calling smallest_first: a = {a}, b = {b}"); smallest_first(&mut a, &mut b); println!("After calling smallest_first: a = {a}, b = {b}"); smallest_first(&mut a, &mut b); println!("After calling smallest_first again: a = {a}, b = {b}"); }
should display
Before calling smallest first: a = 42, b = 10
After calling smallest first: a = 10, b = 42
After calling smallest first again: a = 10, b = 42