如何在 Rust 中交换向量、切片或数组中的项目? [英] How can I swap items in a vector, slice, or array in Rust?
问题描述
我的代码如下所示:
fn swap<T>(mut collection: Vec<T>, a: usize, b: usize) {
let temp = collection[a];
collection[a] = collection[b];
collection[b] = temp;
}
Rust 非常确定我不允许移出取消引用"或移出索引内容",无论是什么.我如何让 Rust 相信这是可能的?
Rust is pretty sure I'm not allowed to "move out of dereference" or "move out of indexed content", whatever that is. How do I convince Rust that this is possible?
推荐答案
有一个 swap
为 &mut [T]
定义的方法.由于 Vec
可以可变解引用作为一个&mut [T]
,可以直接调用这个方法:
There is a swap
method defined for &mut [T]
. Since a Vec<T>
can be mutably dereferenced as a &mut [T]
, this method can be called directly:
fn main() {
let mut numbers = vec![1, 2, 3];
println!("before = {:?}", numbers);
numbers.swap(0, 2);
println!("after = {:?}", numbers);
}
要自己实现这一点,您必须编写一些不安全的代码.Vec::swap
是这样实现的:
To implement this yourself, you have to write some unsafe code. Vec::swap
is implemented like this:
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
以安全地交换它们.
It takes two raw pointers from the vector and uses ptr::swap
to swap them safely.
还有一个 mem::swap(&mut T, &mut T)
当您需要交换两个不同的变量时.这不能在这里使用,因为 Rust 不允许从同一个向量中获取两个可变借用.
There is also a mem::swap(&mut T, &mut T)
when you need to swap two distinct variables. That cannot be used here because Rust won't allow taking two mutable borrows from the same vector.
这篇关于如何在 Rust 中交换向量、切片或数组中的项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!