gpt4 book ai didi

rust - 如何在Rust数组的2个可变切片上进行操作?

转载 作者:行者123 更新时间:2023-12-03 11:47:52 28 4
gpt4 key购买 nike

我有一个需要在单个数组的两个部分上进行操作的函数。
目的是能够构建一个#[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

此模式也可以用于就地快速排序等。

对于同一数组的不重叠切片有两个可变引用,这有什么不安全的方法吗?如果无法用纯Rust进行,是否有“安全的” 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).

关于rust - 如何在Rust数组的2个可变切片上进行操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63712497/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com