如何对 Rust 数组的 2 个可变切片进行操作?
How to operate on 2 mutable slices of a Rust array?
我有一个函数需要对单个数组的两个部分进行操作。
目的是能够构建一个 #[nostd]
分配器,它可以 return 一个更大数组的可变切片给调用者,并保留数组的其余部分以供将来分配。
下面是失败的示例代码:
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
此模式也有助于就地快速排序等
对同一数组的非重叠切片有两个可变引用是否有任何不安全之处?如果在纯 Rust 中没有办法,是否有 "safe" unsafe
允许它继续进行的咒语?
Is there anything unsafe about having two mutable references to nonoverlapping slices of the same array?
没有,但 Rust 的类型系统当前无法检测到您正在对切片的两个非重叠部分进行可变引用。由于这是一个常见的用例,Rust 提供了一个安全的函数来做你想做的事:std::slice::split_at_mut
.
fn split_at_mut(&mut self, mid: usize) -> (&mut [T], &mut [T])
Divides one &mut
into two at an index.
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).
最终代码为:
fn main() {
let mut mem : [i32; 2048] = [1; 2048];
let (mut array0, mut array1) = mem[..].split_at_mut(768);
array0[0] = 4;
println!("{:?} {:?}", array0[0], array1[0]);
}
哇,真是绝配。感谢您找到这个!
我有一个函数需要对单个数组的两个部分进行操作。
目的是能够构建一个 #[nostd]
分配器,它可以 return 一个更大数组的可变切片给调用者,并保留数组的其余部分以供将来分配。
下面是失败的示例代码:
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
此模式也有助于就地快速排序等
对同一数组的非重叠切片有两个可变引用是否有任何不安全之处?如果在纯 Rust 中没有办法,是否有 "safe" unsafe
允许它继续进行的咒语?
Is there anything unsafe about having two mutable references to nonoverlapping slices of the same array?
没有,但 Rust 的类型系统当前无法检测到您正在对切片的两个非重叠部分进行可变引用。由于这是一个常见的用例,Rust 提供了一个安全的函数来做你想做的事:std::slice::split_at_mut
.
fn split_at_mut(&mut self, mid: usize) -> (&mut [T], &mut [T])
Divides one
&mut
into two at an index.The first will contain all indices from
[0, mid)
(excluding the indexmid
itself) and the second will contain all indices from[mid, len)
(excluding the indexlen
itself).
最终代码为:
fn main() {
let mut mem : [i32; 2048] = [1; 2048];
let (mut array0, mut array1) = mem[..].split_at_mut(768);
array0[0] = 4;
println!("{:?} {:?}", array0[0], array1[0]);
}
哇,真是绝配。感谢您找到这个!