当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Rust swap用法及代码示例


本文简要介绍rust语言中 Function core::ptr::swap 的用法。

用法

pub unsafe fn swap<T>(x: *mut T, y: *mut T)

交换同一类型的两个可变位置的值,而不取消初始化任何一个。

但对于以下两个例外,此函数在语义上等价于 mem::swap

  • 它对原始指针而不是引用进行操作。当参考可用时,应该首选 mem::swap

  • 两个指向的值可能重叠。如果这些值确实重叠,则将使用来自x 的重叠内存区域。这在下面的第二个示例中得到了证明。

安全性

如果违反以下任何条件,则行为未定义:

  • 对于读取和写入,xy 都必须是 valid

  • xy 都必须正确对齐。

请注意,即使 T 的大小为 0 ,指针也必须非空且正确对齐。

例子

交换两个不重叠的区域:

use std::ptr;

let mut array = [0, 1, 2, 3];

let x = array[0..].as_mut_ptr() as *mut [u32; 2]; // this is `array[0..2]`
let y = array[2..].as_mut_ptr() as *mut [u32; 2]; // this is `array[2..4]`

unsafe {
    ptr::swap(x, y);
    assert_eq!([2, 3, 0, 1], array);
}

交换两个重叠区域:

use std::ptr;

let mut array: [i32; 4] = [0, 1, 2, 3];

let array_ptr: *mut i32 = array.as_mut_ptr();

let x = array_ptr as *mut [i32; 3]; // this is `array[0..3]`
let y = unsafe { array_ptr.add(1) } as *mut [i32; 3]; // this is `array[1..4]`

unsafe {
    ptr::swap(x, y);
    // The indices `1..3` of the slice overlap between `x` and `y`.
    // Reasonable results would be for to them be `[2, 3]`, so that indices `0..3` are
    // `[1, 2, 3]` (matching `y` before the `swap`); or for them to be `[0, 1]`
    // so that indices `1..4` are `[0, 1, 2]` (matching `x` before the `swap`).
    // This implementation is defined to make the latter choice.
    assert_eq!([1, 0, 1, 2], array);
}

相关用法


注:本文由纯净天空筛选整理自rust-lang.org大神的英文原创作品 Function core::ptr::swap。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。