Slices

Mutable Slices

A mutable slice (&mut [T] or &mut str) is an exclusive, fixed-length view into a contiguous sequence of elements inside a mutable array (let mut arr: [T; N]) or vector (let mut vec: Vec<T>). While a mutable slice cannot change the number of elements in the underlying collection, it can read, overwrite, swap, reverse, or sort any elements within its bounds in place.

Creating and Modifying a Mutable Slice

fn scale_and_reverse(slice: &mut [i32], factor: i32) {
    for elem in slice.iter_mut() {
        *elem *= factor;
    }
    slice.reverse();
}

fn main() {
    let mut numbers = [1, 2, 3, 4, 5];

    // Mutably borrow only the middle 3 elements (`[2, 3, 4]`):
    scale_and_reverse(&mut numbers[1..4], 10);

    println!("Updated array: {numbers:?}");
}
Updated array: [1, 40, 30, 20, 5]

In-Place Mutation Methods on &mut [T]

Method Example on s: &mut [T] In-Place Effect
s[i] = val s[0] = 99; Overwrites the element at index i
s.swap(i, j) s.swap(0, 2); Exchanges s[i] and s[j] without cloning
s.reverse() s.reverse(); Reverses the order of elements in the slice
s.fill(val) s.fill(0); Sets every element in the slice to a clone of val
s.sort() / s.sort_unstable() s.sort(); Sorts elements in ascending order
s.rotate_left(k) / rotate_right(k) s.rotate_left(1); Cyclically shifts elements in $O(n)$ time with $O(1)$ space
s.copy_from_slice(src) s.copy_from_slice(&other) Fast memcpy from src (panics if s.len() != src.len())
s.split_at_mut(mid) let (l, r) = s.split_at_mut(2); Splits one &mut [T] into two non-overlapping &mut [T] slices
fn main() {
    let mut buf = [10, 20, 30, 40];
    buf.swap(0, 3);
    buf.rotate_left(1);
    println!("After swap and rotate_left: {buf:?}");

    let (left, right) = buf.split_at_mut(2);
    left.fill(0);
    right.reverse();
    println!("After split_at_mut edits:   {buf:?}");
}
After swap and rotate_left: [20, 30, 10, 40]
After split_at_mut edits:   [0, 0, 40, 10]

Exclusivity Rule on &mut [T] (E0499)

Indexing &mut arr[0..2] and &mut arr[2..4] directly in two separate statements fails with E0499 because the borrow checker treats both index operations as borrowing the entire arr mutably. Always use arr.split_at_mut(2) (or chunks_mut) to obtain multiple simultaneous &mut sub-slices safely.