本文簡要介紹rust語言中 std::mem::MaybeUninit.as_mut_ptr
的用法。
用法
pub fn as_mut_ptr(&mut self) -> *mut T
獲取指向所包含值的可變指針。除非初始化MaybeUninit<T>
,否則從此指針讀取或將其轉換為引用是未定義的行為。
例子
此方法的正確用法:
use std::mem::MaybeUninit;
let mut x = MaybeUninit::<Vec<u32>>::uninit();
x.write(vec![0, 1, 2]);
// Create a reference into the `MaybeUninit<Vec<u32>>`.
// This is okay because we initialized it.
let x_vec = unsafe { &mut *x.as_mut_ptr() };
x_vec.push(3);
assert_eq!(x_vec.len(), 4);
此方法的錯誤使用:
use std::mem::MaybeUninit;
let mut x = MaybeUninit::<Vec<u32>>::uninit();
let x_vec = unsafe { &mut *x.as_mut_ptr() };
// We have created a reference to an uninitialized vector! This is undefined behavior. ⚠️
(請注意,有關對未初始化數據的引用的規則尚未最終確定,但在確定之前,建議避免使用它們。)
相關用法
- Rust MaybeUninit.as_ptr用法及代碼示例
- Rust MaybeUninit.assume_init_mut用法及代碼示例
- Rust MaybeUninit.assume_init_ref用法及代碼示例
- Rust MaybeUninit.assume_init用法及代碼示例
- Rust MaybeUninit.assume_init_read用法及代碼示例
- Rust MaybeUninit.array_assume_init用法及代碼示例
- Rust MaybeUninit.write_slice用法及代碼示例
- Rust MaybeUninit.zeroed用法及代碼示例
- Rust MaybeUninit.write_slice_cloned用法及代碼示例
- Rust MaybeUninit.write用法及代碼示例
- Rust MaybeUninit.uninit用法及代碼示例
- Rust MaybeUninit.new用法及代碼示例
- Rust MaybeUninit.uninit_array用法及代碼示例
- Rust MaybeUninit用法及代碼示例
- Rust ManuallyDrop用法及代碼示例
- Rust ManuallyDrop.into_inner用法及代碼示例
- Rust ManuallyDrop.new用法及代碼示例
- Rust Map用法及代碼示例
- Rust Mutex.new用法及代碼示例
- Rust MetadataExt.st_ctime_nsec用法及代碼示例
- Rust MetadataExt.mtime_nsec用法及代碼示例
- Rust MetadataExt.nlink用法及代碼示例
- Rust MulAssign.mul_assign用法及代碼示例
- Rust Mutex.get_mut用法及代碼示例
- Rust MetadataExt.st_atime用法及代碼示例
注:本文由純淨天空篩選整理自rust-lang.org大神的英文原創作品 std::mem::MaybeUninit.as_mut_ptr。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。