#17765·rust-clippy

Add lint for `mem::swap`ping lock-guarded values.

Author: selendymCreated Sep 21, 2026Updated Sep 30, 2026
Labelsgood first issueA-lint

What it does

Warn when lock-guarded values are swapped without dereferencing first.

rust
mem::swap(&mut a_guard, &mut b_guard); // probably incorrect: swaps the locks
mem::swap(&mut *a_guard, &mut *b_guard); // probably intended: swaps the locked values

Advantage

Might catch logic errors.

Drawbacks

An explicit clippy-allow may be required to get rid of a warning, depending on what category this lint is to be. A false positive is likely rare in practice and an explicit allow would serve as documentation of the intention. I'd suggest clippy::suspicious as the category.

Example

The examples below use RefCell for the locks, but the lint should cover other similar locks in std, like Mutex, too.

An example where the lint should trigger:

rust
fn main() {
    use std::{cell::RefCell, mem};

    let a = RefCell::new(1_i32);
    let b = RefCell::new(2_i32);

    {
        let mut a_guard = a.borrow_mut();
        let mut b_guard = b.borrow_mut();
        mem::swap(&mut a_guard, &mut b_guard); // probably incorrect: swaps the locks
    }

    println!("a: {}, b: {}", *a.borrow(), *b.borrow()); // prints "a: 1, b: 2"
}

Below is what was probably intended. The only difference is the added dereference operators * before the guard variables in mem::swap arguments.

rust
fn main() {
    use std::{cell::RefCell, mem};

    let a = RefCell::new(1_i32);
    let b = RefCell::new(2_i32);

    {
        let mut a_guard = a.borrow_mut();
        let mut b_guard = b.borrow_mut();
        mem::swap(&mut *a_guard, &mut *b_guard); // probably intended: swaps the locked values
    }

    println!("a: {}, b: {}", *a.borrow(), *b.borrow()); // prints "a: 2, b: 1"
}

Comparison with existing lints

swap_with_temporary might be the closest match currently, but it doesn't seem to trigger here.

Additional Context

No response