mem::swap() 函数

用于交换相同类型的两个可变更引用.

该函数的接口声明如下:

#![allow(unused)]
fn main() {
pub fn swap<T>(x: &mut T, y: &mut T);
}

下面是一个简单的用例程序:

use std::mem;

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

    mem::swap(&mut x[0], &mut y[0]);
    assert_eq!(x, [4, 2, 3]);
    assert_eq!(y, [1, 5]);
}

swap() 函数的实现

该函数的源代码如下:

#![allow(unused)]

fn main() {
#[inline]
pub const fn swap<T>(x: &mut T, y: &mut T) {
    // SAFETY: `&mut` guarantees these are typed readable and writable
    // as well as non-overlapping.
    unsafe { intrinsics::typed_swap(x, y) }
}

mod intrinsics {
    #[inline]
    #[rustc_intrinsic]
    pub const unsafe fn typed_swap<T>(x: *mut T, y: *mut T) {
        // SAFETY: The caller provided single non-overlapping items behind
        // pointers, so swapping them with `count: 1` is fine.
        unsafe { ptr::swap_nonoverlapping(x, y, 1) };
    }
}
}

可以看到, 这个函数仅仅使用了 ptr::swap_nonoverlapping().