Skip to content

Commit dc570fb

Browse files
committed
also add examples to MaybeUninit::into_initialized
1 parent 13ffbee commit dc570fb

File tree

1 file changed

+28
-1
lines changed

1 file changed

+28
-1
lines changed

src/libcore/mem.rs

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1178,6 +1178,31 @@ impl<T> MaybeUninit<T> {
11781178
/// It is up to the caller to guarantee that the `MaybeUninit` really is in an initialized
11791179
/// state. Calling this when the content is not yet fully initialized causes undefined
11801180
/// behavior.
1181+
///
1182+
/// # Examples
1183+
///
1184+
/// Correct usage of this method:
1185+
///
1186+
/// ```rust
1187+
/// #![feature(maybe_uninit)]
1188+
/// use std::mem::MaybeUninit;
1189+
///
1190+
/// let mut x = MaybeUninit::<bool>::uninitialized();
1191+
/// x.set(true);
1192+
/// let x_init = unsafe { x.into_initialized() };
1193+
/// assert_eq!(x_init, true);
1194+
/// ```
1195+
///
1196+
/// *Incorrect* usage of this method:
1197+
///
1198+
/// ```rust,no_run
1199+
/// #![feature(maybe_uninit)]
1200+
/// use std::mem::MaybeUninit;
1201+
///
1202+
/// let x = MaybeUninit::<Vec<u32>>::uninitialized();
1203+
/// let x_init = unsafe { x.into_initialized() };
1204+
/// // `x` had not been initialized yet, so this last line causes undefined behavior.
1205+
/// ```
11811206
#[unstable(feature = "maybe_uninit", issue = "53491")]
11821207
#[inline(always)]
11831208
pub unsafe fn into_initialized(self) -> T {
@@ -1212,15 +1237,17 @@ impl<T> MaybeUninit<T> {
12121237
/// let x1 = unsafe { x.read_initialized() };
12131238
/// // `u32` is `Copy`, so we may read multiple times.
12141239
/// let x2 = unsafe { x.read_initialized() };
1240+
/// assert_eq!(x1, x2);
12151241
///
12161242
/// let mut x = MaybeUninit::<Option<Vec<u32>>>::uninitialized();
12171243
/// x.set(None);
12181244
/// let x1 = unsafe { x.read_initialized() };
12191245
/// // Duplicating a `None` value is okay, so we may read multiple times.
12201246
/// let x2 = unsafe { x.read_initialized() };
1247+
/// assert_eq!(x1, x2);
12211248
/// ```
12221249
///
1223-
/// *Incorrect* usafe of this method:
1250+
/// *Incorrect* usage of this method:
12241251
///
12251252
/// ```rust,no_run
12261253
/// #![feature(maybe_uninit)]

0 commit comments

Comments
 (0)