Split At Mut For Disjoint Borrows
Split one slice into two non-overlapping mutable halves with split_at_mut, the sanctioned way to edit disjoint regions the borrow checker can prove safe.
Code
fn swap_ends(values: &mut [i32]) {
if values.len() < 2 {
return;
}
let (middle, tail) = values.split_at_mut(values.len() - 1);
// middle[0] 与 tail[0] 是两个独立的 &mut,借用互不重叠
std::mem::swap(&mut middle[0], &mut tail[0]);
}
fn main() {
let mut readings = [10, 20, 30, 40];
// 同一片切成两段互不相交的 &mut:一段加倍、另一段自增
let (left, right) = readings.split_at_mut(2);
left[0] *= 2;
right[0] += 1;
println!("after edits: {readings:?}");
// 函数边界上同样成立:交换首尾不需要两次可变索引
swap_ends(&mut readings);
println!("after swap: {readings:?}");
}How it works
Split At Mut For Disjoint Borrows keeps everything in the functions swap_ends and main.
Using it
Entry signature: fn swap_ends(values: &mut [i32])
The demo output is labeled (after edits:, after swap:), so every printed line maps back to its originating operation.
Launch the file; main takes over and steps through swap_ends.
Key statements
fn swap_ends(values: &mut [i32]) {
if values.len() < 2 {
return;
}
let (middle, tail) = values.split_at_mut(values.len() - 1);
// middle[0] 与 tail[0] 是两个独立的 &mut,借用互不重叠
std::mem::swap(&mut middle[0], &mut tail[0]);
}
right[0] += 1;
Interactive Tools for This Topic
FAQ
- What does Split At Mut For Disjoint Borrows print when run?
- No setup needed: run the file and look for labeled lines like `after edits:`, `after swap:` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.