Articles / Rust

  • rust
  • borrow-checker
  • ownership
  • mutex
  • closures
  • debugging

Why Borrowing Two Fields Works Until You Hide One Behind a Method

You can loop over one field of a struct while pushing to another, and Rust is perfectly happy. Tidy that field access into a getter and the same logic stops compiling. The memory is exactly as it was, but the compiler is now allowed to know less about it.

Here is the version that works:

struct Server {
    clients: Vec<String>,
    log: Vec<String>,
}

fn direct(s: &mut Server) {
    for c in &mut s.clients {
        s.log.push(c.clone());
        c.push('!');
    }
}

And here is the "cleaned up" one:

impl Server {
    fn clients_mut(&mut self) -> &mut Vec<String> {
        &mut self.clients
    }

    fn record(&mut self, line: &str) {
        self.log.push(line.to_owned());
    }
}

fn hidden(s: &mut Server) {
    for c in s.clients_mut() {
        s.record(c);
    }
}

The compiler rejects it with error[E0499]: cannot borrow `*s` as mutable more than once at a time.

The checker tracks fields, but only where it can see them

Inside a single function body, the borrow checker reasons about places: paths such as s.clients and s.log. Two different fields of a struct cannot overlap, so a mutable borrow of one says nothing about the other.

A method call is different. When checking hidden, the compiler does not look inside clients_mut. It reads the signature, which with the elided lifetimes written out is this:

fn clients_mut<'a>(&'a mut self) -> &'a mut Vec<String>

That says: give me exclusive access to the whole of self, and for as long as you hold the result, that access continues. The word "clients" in the method name is for humans. The type system gets nothing from it.

So the loop holds all of *s mutably, and s.record(c) asks for all of *s again. Both requests are honest readings of the signatures, and they conflict.

Quick detour: why not just look inside?

It feels daft. The body is one line and it is right there. But if callers were checked against bodies, editing a body could break code far away without any signature changing.

Today you can rewrite clients_mut to bump a counter in another field first, and every caller still compiles. For a library, that is the difference between a patch release and a very annoyed bug tracker. The signature is the contract, including the parts you wish it didn't promise.

A MutexGuard hides a method you never typed

This version tends to cause real confusion, because there is no getter anywhere in sight:

fn guarded(m: &Mutex<Server>) {
    let mut guard = m.lock().unwrap();
    for c in &guard.clients {
        guard.log.push(c.clone()); // error[E0502]
    }
}

It looks like plain field access. It isn't: guard is a MutexGuard, so reaching clients calls Deref::deref(&guard), and pushing to log calls DerefMut::deref_mut(&mut guard). Those are methods, and each borrows the whole guard.

The fix is one line. Dereference once, then split the fields of the plain reference:

fn guarded(m: &Mutex<Server>) {
    let mut guard = m.lock().unwrap();
    let s = &mut *guard;
    for c in &s.clients {
        s.log.push(c.clone());
    }
}

deref_mut now runs a single time, and s is an ordinary &mut Server whose fields the checker can see. The same trick works for RefMut from a RefCell.

Side-path, because it is odd: Box<Server> does not have this problem. The compiler has built-in knowledge of Box and lets you borrow separate fields straight through it. Your own smart pointer gets no such favour.

Fix it by telling the compiler which fields you mean

You have a few options, and they suit different situations:

  • Access the fields directly, where privacy allows it.
  • Pass individual fields to a function instead of passing &mut self.
  • Write one method that returns both borrows together.
  • Group fields that are used together into their own struct, and put the methods on that.

The second and third combine nicely:

impl Server {
    fn parts_mut(&mut self) -> (&mut Vec<String>, &mut Vec<String>) {
        (&mut self.clients, &mut self.log)
    }
}

fn record(log: &mut Vec<String>, line: &str) {
    log.push(line.to_owned());
}

fn split(s: &mut Server) {
    let (clients, log) = s.parts_mut();
    for c in clients {
        record(log, c);
    }
}

parts_mut still borrows all of self, but it hands back two references the caller can use independently, and the compiler has checked inside the method that they do not overlap.

The catch is that this exposes your layout through the signature. For private helpers that is usually fine. In a public API, think about whether you want to promise that those two things will always be separately borrowable.

I would reach for the sub-struct when the same pair keeps turning up. A parts_mut that has grown to a five-element tuple is the struct telling you it is really two or three structs.

Closures can see fields, methods cannot say them

Since the 2021 edition, closures capture the individual fields they use, not necessarily the whole variable. This compiles:

fn closure(s: &mut Server) {
    let mut add = |line: &str| s.log.push(line.to_owned());
    for c in &s.clients {
        add(c);
    }
}

The closure borrows only s.log. This works because a closure is defined inside the function being checked, so the compiler can infer exactly what it captures without making that part of anyone's public contract.

Call s.record(line) inside the closure instead and you are back where you started, since record demands all of s.

Slices need help even without a method

Fields have names the compiler can compare. Indices are values, possibly only known at run time, so it does not try to prove that v[i] and v[j] are different elements.

The standard library has methods that do the checking and return separate references, such as split_at_mut and, since Rust 1.86, get_disjoint_mut:

let mut v = [1, 2, 3];
let [x, y] = v.get_disjoint_mut([0, 2]).unwrap();
std::mem::swap(x, y);
assert_eq!(v, [3, 2, 1]);

It returns an error if an index is out of bounds or two of them overlap. It is the same bargain as parts_mut: one borrow goes in, several non-overlapping ones come out.

When you hit the original error, resist the urge to clone() the whole collection first. It does compile, but a loop that clones clients and then mutates the clone's strings will quietly leave the originals untouched. The borrow error was annoying; that bug is worse.