作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个需要在单个数组的两个部分上进行操作的函数。
目的是能够构建一个#[nostd]
分配器,该分配器可以将更大数组的可变切片返回给调用方,并保留到数组的其余部分以供将来分配。
这是失败的示例代码:
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
unsafe
咒语可以使它继续进行?
最佳答案
Is there anything unsafe about having two mutable references to nonoverlapping slices of the same array?
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).
关于rust - 如何在Rust数组的2个可变切片上进行操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63712497/
我是一名优秀的程序员,十分优秀!