I have a function that should work on two parts of the same array. The goal is to be able to compose the #[nostd] , which can return a variable slice of a larger array to the caller and insert the remainder of the array for future distributions.
Here is an example of failed code:
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]); }
the error is this:
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 template can also be useful for quick sorting in place, etc.
Is there anything unsafe about having two mutable references to non-overlapping fragments of the same array? If there is no way in pure rust, is there a "safe" unsafe spell that will allow it to continue?
source share