不可以直接用std::mem::swap
,因为这个函数需要拿两个可变引用,但是不可以同时拿两个这个数组的可变引用。
所以要么手写:
let tmp = a[i];
= a[j];
a[i] = tmp; a[j]
要么用Vec::swap
:
.swap(i, j); a
其内部实现:
fn swap(&mut self, a: usize, b: usize) {
unsafe {
// Can't take two mutable loans from one vector, so instead just cast
// them to their raw pointers to do the swap
let pa: *mut T = &mut self[a];
let pb: *mut T = &mut self[b];
ptr::swap(pa, pb);
}
}