RS.CLIPPY.SWAP_WITH_TEMPORARY

Detect swap with a temporary value

This checker is a Clippy lint created by The Rust Project Contributors. The documentation shown here is a copy of the original documentation for: swap_with_temporary. Copyright ©2025 The Rust Team. All rights reserved.

What it does

Checks for usage of std::mem::swap with temporary values.

Why is this bad?

Storing a new value in place of a temporary value which will be dropped right after the swap is an inefficient way of performing an assignment. The same result can be achieved by using a regular assignment.

Examples

fn replace_string(s: &mut String) {
    std::mem::swap(s, &mut String::from("replaced"));
}

Use instead:

fn replace_string(s: &mut String) {
    *s = String::from("replaced");
}

Also, swapping two temporary values has no effect, as they will both be dropped right after swapping them. This is likely an indication of a bug. For example, the following code swaps the references to the last element of the vectors, instead of swapping the elements themselves:

fn bug(v1: &mut [i32], v2: &mut [i32]) {
    // Incorrect: swapping temporary references (`&mut &mut` passed to swap)
    std::mem::swap(&mut v1.last_mut().unwrap(), &mut v2.last_mut().unwrap());
}

Use instead:

fn correct(v1: &mut [i32], v2: &mut [i32]) {
    std::mem::swap(v1.last_mut().unwrap(), v2.last_mut().unwrap());
}