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


Rust MaybeUninit.assume_init_ref用法及代碼示例


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

用法

pub unsafe fn assume_init_ref(&self) -> &T

獲取對包含值的共享引用。

當我們想要訪問已初始化但沒有 MaybeUninit 所有權的 MaybeUninit (防止使用 .assume_init() )時,這可能很有用。

安全性

當內容尚未完全初始化時調用此方法會導致未定義的行為:由調用者來保證 MaybeUninit<T> 確實處於初始化狀態。

例子

此方法的正確用法:
use std::mem::MaybeUninit;

let mut x = MaybeUninit::<Vec<u32>>::uninit();
// Initialize `x`:
x.write(vec![1, 2, 3]);
// Now that our `MaybeUninit<_>` is known to be initialized, it is okay to
// create a shared reference to it:
let x: &Vec<u32> = unsafe {
    // SAFETY: `x` has been initialized.
    x.assume_init_ref()
};
assert_eq!(x, &vec![1, 2, 3]);
不正確此方法的用法:
use std::mem::MaybeUninit;

let x = MaybeUninit::<Vec<u32>>::uninit();
let x_vec: &Vec<u32> = unsafe { x.assume_init_ref() };
// We have created a reference to an uninitialized vector! This is undefined behavior. ⚠️
use std::{cell::Cell, mem::MaybeUninit};

let b = MaybeUninit::<Cell<bool>>::uninit();
// Initialize the `MaybeUninit` using `Cell::set`:
unsafe {
    b.assume_init_ref().set(true);
   // ^^^^^^^^^^^^^^^
   // Reference to an uninitialized `Cell<bool>`: UB!
}

相關用法


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