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


Rust MaybeUninit.write_slice用法及代碼示例


本文簡要介紹rust語言中 std::mem::MaybeUninit.write_slice 的用法。

用法

pub fn write_slice(this: &'a mut [MaybeUninit<T>], src: &[T]) -> &'a mut [T] where    T: Copy,

將元素從 src 複製到 this ,返回對現在初始化的 this 內容的可變引用。

如果 T 未實現 Copy ,請使用 write_slice_cloned

這類似於 slice::copy_from_slice

Panics

如果兩個切片的長度不同,此函數將出現Panics。

例子

#![feature(maybe_uninit_write_slice)]
use std::mem::MaybeUninit;

let mut dst = [MaybeUninit::uninit(); 32];
let src = [0; 32];

let init = MaybeUninit::write_slice(&mut dst, &src);

assert_eq!(init, src);
#![feature(maybe_uninit_write_slice, vec_spare_capacity)]
use std::mem::MaybeUninit;

let mut vec = Vec::with_capacity(32);
let src = [0; 16];

MaybeUninit::write_slice(&mut vec.spare_capacity_mut()[..src.len()], &src);

// SAFETY: we have just copied all the elements of len into the spare capacity
// the first src.len() elements of the vec are valid now.
unsafe {
    vec.set_len(src.len());
}

assert_eq!(vec, src);

相關用法


注:本文由純淨天空篩選整理自rust-lang.org大神的英文原創作品 std::mem::MaybeUninit.write_slice。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。