我是Rust的新手,我正在尝试在Vec<i32>
函数中获取swap()
元素并更改它:
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;
}
我应该将元素设置为可变元素?
如果我尝试在swap(vec.index(i), vec.index(i+1));
中执行,则会显示error: cannot borrow immutable borrowed content as mutable