我的代码如下所示:
fn swap<T>(mut collection: Vec<T>, a: usize, b: usize) {
let temp = collection[a];
collection[a] = collection[b];
collection[b] = temp;
}
Rust非常确定我不被允许"移出go 引用"或"移出索引内容",不管是什么.我如何让Rust相信这是可能的?
我的代码如下所示:
fn swap<T>(mut collection: Vec<T>, a: usize, b: usize) {
let temp = collection[a];
collection[a] = collection[b];
collection[b] = temp;
}
Rust非常确定我不被允许"移出go 引用"或"移出索引内容",不管是什么.我如何让Rust相信这是可能的?
有一个swap
method defined for &mut [T]
.由于Vec<T>
可以是mutably dereferenced,也可以是&mut [T]
,因此可以直接调用此方法:
fn main() {
let mut numbers = vec![1, 2, 3];
println!("before = {:?}", numbers);
numbers.swap(0, 2);
println!("after = {:?}", numbers);
}
要自己实现这一点,必须编写一些不安全的代码.Vec::swap
is implemented个像这样:
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);
}
}
它从向量中提取两个原始指针,并使用ptr::swap
安全地交换它们.
当你需要交换两个不同的变量时,也有一个mem::swap(&mut T, &mut T)
.这在这里不能使用,因为Rust不允许从同一个向量获取两个可变的借词.