skip to content

In Rust, why do `&mut img[..mid]` and `&mut img[mid..]` held together fail with E0499, and how does `split_at_mut` fix it?

level: middleimportance: should knowfreq 50%

answer

  1. what index_mut takes as its receiver
  2. the checker does no index arithmetic
  3. one call, two halves
  4. mid greater than len

basics

~10 s

Each &mut img[..] calls IndexMut::index_mut(&mut img, ..), so both slices borrow all of img mutably and rustc reports E0499; it never compares index ranges. split_at_mut(mid) borrows once and returns two non-overlapping &mut [T] halves.

solid answer

~40 s

`&mut img[..mid]` on a `Vec` desugars to `IndexMut::index_mut(&mut img, ..mid)`, which takes `&mut self`, so to the borrow checker the whole of `img` is exclusively borrowed. It does no arithmetic on index ranges, so a second `&mut img[mid..]` is a second exclusive borrow and fails with E0499; rustc even prints a help line suggesting `.split_at_mut(position)`. `split_at_mut(mid)` borrows `img` once and returns `(&mut [T], &mut [T])` covering `[0, mid)` and `[mid, len)`; std guarantees they do not overlap, using `unsafe` internally. It panics if `mid > len`, and `split_at_mut_checked` (Rust 1.80) returns `None` instead. For fixed-size rows use `chunks_mut`, and for a few arbitrary indices `get_disjoint_mut` (Rust 1.86).

code

rust · 8 lines
rust
fn main() {
    let mut img = vec![10u8, 20, 30, 40, 200, 210, 220, 230];
    let mid = img.len() / 2;
    let top = &mut img[..mid];
    let bottom = &mut img[mid..];
    top[0] = 0;
    bottom[0] = 255;
}

go deeper

for a junior

Recall that two mutable borrows of the same Vec cannot be alive at once, and that split_at_mut is the standard way to get two mutable halves.

for a middle

Explain that index_mut takes &mut self so each index borrows the whole Vec, that borrowck does no range arithmetic, and that split_at_mut panics when mid exceeds the length.

for a senior

Pick the right splitter for the job: split_at_mut for halves, chunks_mut for rows, get_disjoint_mut for scattered indices, and say why copying a half out is the wrong fix.

for a principal

Point out that split_at_mut is the model for wrapping unsafe in a safe signature, and that a team's own split helpers should follow it rather than handing out raw pointers.

## The failing code An image tool wants to brighten the top half of a pixel buffer and invert the bottom half: ```rust let mut img = vec![10u8, 20, 30, 40, 200, 210, 220, 230]; let mid = img.len() / 2; let top = &mut img[..mid]; let bottom = &mut img[mid..]; top[0] = 0; bottom[0] = 255; ``` rustc 1.99.1 rejects it, and its own help line names the fix: ```plaintext error[E0499]: cannot borrow `img` as mutable more than once at a time = help: use `.split_at_mut(position)` to obtain two mutable non-overlapping sub-slices ``` ## Why the borrow checker says no - **Indexing a `Vec` is a method call.** `&mut img[..mid]` is sugar for `IndexMut::index_mut(&mut img, ..mid)`. The receiver is `&mut self`, so the exclusive borrow covers the entire `img`, not the range. - **The checker does not compare index ranges.** The Rustonomicon says it plainly: borrowck "doesn't understand arrays or slices in any way". Proving that `..mid` and `mid..` are disjoint needs arithmetic on run-time values, which it does not attempt; even `&mut a[0]` and `&mut a[1]` conflict. - **Struct fields are different.** For a struct the checker tracks each field as its own place, so `&mut frame.top` and `&mut frame.bottom` coexist. There the disjointness is visible in the source; for indices it is not. The rule being protected is that two `&mut` must never alias. The compiler cannot prove these two do not, so it refuses. ## What `split_at_mut` does `<[T]>::split_at_mut(&mut self, mid: usize) -> (&mut [T], &mut [T])` takes one exclusive borrow and returns two fat pointers, one covering `[0, mid)` and one covering `[mid, len)`. ```rust let (top, bottom) = img.split_at_mut(mid); brighten(top); invert(bottom); img.push(0); // fine: top and bottom are no longer used ``` 1. The call borrows `img` exclusively **once**, for as long as either half is used; after their last use `img` is free again. 2. Inside, std builds both halves from one raw pointer with `unsafe` code, since no safe primitive can express the split; the safe signature is the promise that they never overlap. (How such unsafe code is justified is covered with sound unsafe abstractions.) 3. Its doc comment says it panics if `mid > len`, with the message `mid > len`. `mid == len` is fine and gives an empty second half. 4. `split_at_mut_checked`, stable since Rust 1.80, returns `None` instead of panicking. Because the halves are ordinary `&mut [u8]` values, each can go to a different function, or to a different thread inside `std::thread::scope`, since the two alias nothing (spawning is covered with threads). ## The family of splitting methods | Need | Method | Returns | |---|---|---| | Two halves at a point | `split_at_mut(mid)` | `(&mut [T], &mut [T])`, panics if `mid > len` | | The same, without a panic | `split_at_mut_checked(mid)` | `Option<(&mut [T], &mut [T])>`, Rust 1.80 | | The first element and the rest | `split_first_mut()` | `Option<(&mut T, &mut [T])>` | | Fixed-width rows of an image | `chunks_mut(width)` | an iterator of `&mut [T]` | | A few scattered indices | `get_disjoint_mut([i, j])` | `Result<[&mut T; N], GetDisjointMutError>`, Rust 1.86 | `get_disjoint_mut` checks at run time that every index is in bounds and that none overlap, and returns an error otherwise. Its doc comment warns that the overlap check is O(n²), which is fine for two or three indices and wrong for hundreds. For an image stored row by row, `chunks_mut` is usually the better tool than repeated splitting: ```rust let width = 4; for row in img.chunks_mut(width) { row.reverse(); // mirror each row in place } ``` Each `row` is a `&mut [u8]` of `width` pixels (the last one shorter if the length is not a multiple), and the iterator guarantees the rows never overlap. `chunks_exact_mut` does the same but leaves a short tail out of the iteration and exposes it through `into_remainder`, which keeps the loop body free of a length check. ## What to say in an interview - Name the cause precisely: `index_mut` borrows the whole container, and borrowck does no index arithmetic. - Contrast it with struct fields, which the checker does split. - Give `split_at_mut` and its panic condition, then the alternatives for rows (`chunks_mut`) and scattered indices (`get_disjoint_mut`). - Reject the expensive workaround: copying one half into a new `Vec` and writing it back costs an allocation and two copies that `split_at_mut` avoids.

  • How does `split_at_mut` produce two `&mut` from one without breaking the aliasing rule?
    It checks `mid <= len`, takes the slice's raw pointer with `as_mut_ptr`, and builds the halves with `from_raw_parts_mut(ptr, mid)` and `from_raw_parts_mut(ptr.add(mid), len - mid)`. The two ranges share no element, so no memory is reachable through both references. The `unsafe` is sealed inside a safe signature, which is what makes the method sound to call.
  • Why can `&mut frame.top` and `&mut frame.bottom` coexist when two index borrows of one `Vec` cannot?
    Field accesses name distinct places that the compiler can see in the source, so the borrow checker tracks `frame.top` and `frame.bottom` separately. An index is a run-time value passed to `index_mut`, whose `&mut self` receiver borrows the whole container, so the checker cannot tell two ranges apart.
  • How would you run the two filters on separate threads?
    Split first, then spawn inside `std::thread::scope` (stable since Rust 1.63): `s.spawn(|| brighten(top)); s.spawn(|| invert(bottom));`. Each closure captures one `&mut [u8]` half, the halves never overlap, and the scope joins both threads before `img` can be touched again, so no `Arc` or lock is needed.

  • The two ranges overlap at index mid, which is why rustc rejects them.
  • split_at_mut copies each half into a new buffer.
  • split_at_mut returns None when mid is past the end.
  • Getting two &mut into one buffer always needs unsafe in your own code.
  • The borrow checker tracks index ranges but cannot prove mid is in bounds.

Assumes Rust 1.99 on edition 2024; split_at_mut is stable since 1.0, split_at_mut_checked needs 1.80 and get_disjoint_mut needs 1.86.