I'm new to Rust and I'm trying to get Vec<i32>
element in swap()
function and change it:
use std::ops::Index;
fn main() {
let mut vec = Vec::new();
for i in 0..10 {
vec.push(i);
print!("{} ", i);
}
println!(" <- Before sort");
bubble_sort(&mut vec);
for i in &vec {
print!("{} ", i);
}
println!(" <- After sort");
}
fn bubble_sort(vec: &mut Vec<i32>) {
for j in 0..(vec.len() - 1) {
for i in 0..(vec.len() - j - 1) {
if vec[i] < vec[i + 1] {
swap(vec.index(i), vec.index(i + 1));
}
}
}
}
fn swap<'l>(a: &'l mut i32, b: &'l mut i32) {
let temp = *a;
*a = *b;
*b = temp;
}
Where I should set elements as mutable?
If I trying do it in swap(vec.index(i), vec.index(i+1));
it says error: cannot borrow immutable borrowed content as mutable