本文介绍了如何在Rust数组的2个可变切片上进行操作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

将一个&mut分为两个索引.

第一个将包含[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个可变切片上进行操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 06:31