Skip to content

Commit 084ee7a

Browse files
committed
examples for MaybeUninit::zeroed
1 parent 48aa59e commit 084ee7a

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

src/libcore/mem.rs

+29
Original file line numberDiff line numberDiff line change
@@ -1141,6 +1141,35 @@ impl<T> MaybeUninit<T> {
11411141
///
11421142
/// Note that dropping a `MaybeUninit` will never call `T`'s drop code.
11431143
/// It is your responsibility to make sure `T` gets dropped if it got initialized.
1144+
///
1145+
/// # Example
1146+
///
1147+
/// Correct usage of this method: initializing a struct with zero, where all
1148+
/// fields of the struct can hold 0 as a valid value.
1149+
///
1150+
/// ```rust
1151+
/// #![feature(maybe_uninit)]
1152+
/// use std::mem::MaybeUninit;
1153+
///
1154+
/// let x = MaybeUninit::<(u8, bool)>::zeroed();
1155+
/// let x = unsafe { x.into_initialized() };
1156+
/// assert_eq!(x, (0, false));
1157+
/// ```
1158+
///
1159+
/// *Incorrect* usage of this method: initializing a struct with zero, where some fields
1160+
/// cannot hold 0 as a valid value.
1161+
///
1162+
/// ```rust,no_run
1163+
/// #![feature(maybe_uninit)]
1164+
/// use std::mem::MaybeUninit;
1165+
///
1166+
/// enum NotZero { One = 1, Two = 2 };
1167+
///
1168+
/// let x = MaybeUninit::<(u8, NotZero)>::zeroed();
1169+
/// let x = unsafe { x.into_initialized() };
1170+
/// // We create a `NotZero` (inside a pair) that does not have a valid discriminant.
1171+
/// // This is undefined behavior.
1172+
/// ```
11441173
#[unstable(feature = "maybe_uninit", issue = "53491")]
11451174
#[inline]
11461175
pub fn zeroed() -> MaybeUninit<T> {

0 commit comments

Comments
 (0)