问题描述
我有一个函数需要对单个数组的两个部分进行操作.目的是能够构建一个 #[nostd]
分配器,该分配器可以将更大数组的可变切片返回给调用者,并保留数组的其余部分以供将来分配.
I have a function that needs to operate on two parts of a single array.The purpose is to be able to build an #[nostd]
allocator that can return a variable slice of a bigger array to the caller and hang on to the remainder of the array for future allocations.
这是失败的示例代码:
fn split<'a>(mut item: &'a mut [i32], place: usize) -> (&'a mut [i32], &'a mut [i32]) {
(&mut item[0..place], &mut item[place..])
}
fn main() {
let mut mem: [i32; 2048] = [1; 2048];
let (mut array0, mut array1) = split(&mut mem[..], 768);
array0[0] = 4;
println!("{:?} {:?}", array0[0], array1[0]);
}
错误如下:
error[E0499]: cannot borrow `*item` as mutable more than once at a time
--> src/main.rs:2:32
|
2 | (&mut item[0..place], &mut item[place..])
| ---- ^^^^ second mutable borrow occurs here
| |
| first mutable borrow occurs here
3 | }
| - first borrow ends here
这种模式也有助于就地快速排序等.
This pattern also can be helpful for in-place quicksort, etc.
对同一个数组的非重叠切片有两个可变引用有什么不安全的吗?如果在纯 Rust 中没有办法,是否有一个安全的"unsafe
咒语可以让它继续进行?
Is there anything unsafe about having two mutable references to nonoverlapping slices of the same array? If there's no way in pure Rust, is there a "safe" unsafe
incantation that will allow it to proceed?
推荐答案
没有,但 Rust 的类型系统目前无法检测到您正在对切片的两个不重叠部分进行可变引用.由于这是一个常见的用例,Rust 提供了一个安全的函数来做你想做的事情:std::slice::split_at_mut
.
There isn't, but Rust's type system cannot currently detect that you're taking mutable references to two non-overlapping parts of a slice. As this is a common use case, Rust provides a safe function to do exactly what you want: std::slice::split_at_mut
.
fn split_at_mut(&mut self, mid: usize) ->(&mut [T], &mut [T])
在一个索引处将一个 &mut
一分为二.
Divides one &mut
into two at an index.
第一个将包含来自 [0, mid)
的所有索引(不包括索引mid
本身),第二个将包含来自 [mid, len)
的所有索引(不包括索引 len
本身).
The first will contain all indices from [0, mid)
(excluding the index mid
itself) and the second will contain all indices from [mid, len)
(excluding the index len
itself).
这篇关于如何对 Rust 数组的 2 个可变切片进行操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!