當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。