I'm trying to swap two integers in Rust without any library.
fn main() {
let mut a = 5;
let mut b = 6;
swap(&mut a, &mut b);
println!("{}, {}", a, b); // expecting 6, 5
}
First I've tried:
fn swap(mut a: &mut u32, mut b: &mut u32) {
(a, b) = (b, a); // destructuring assignments are not currently supported
}
Then:
fn swap(mut a: &mut u32, mut b: &mut u32) {
let temp = a;
a = b;
b = temp;
}
// got error[E0623]: lifetime mismatch
Finally:
fn swap<'a>(mut a: &'a mut u32, mut b: &'a mut u32) {
let temp = a;
a = b;
b = temp;
}
// still does not work; when this scope ends a and b in `main()` are still 5 and 6 respectively
// got warning: value assigned to `a` is never read (for `b` as well)
I don't know what's wrong; last implementation looks cumbersome to me but I think it should work as I am passing mutable reference to function, but it does not work.