diff options
| author | Ralf Jung <post@ralfj.de> | 2019-02-22 22:35:18 +0100 |
|---|---|---|
| committer | Ralf Jung <post@ralfj.de> | 2019-02-22 22:37:54 +0100 |
| commit | 084ee7a875cb02c0f0c0c6d1ffaff81d69cec74e (patch) | |
| tree | 3882a8d414c393824eca04beab48d7af947987d9 | |
| parent | 48aa59e74d6a2b3fea5162eaed902798dc0f95f8 (diff) | |
| download | rust-084ee7a875cb02c0f0c0c6d1ffaff81d69cec74e.tar.gz rust-084ee7a875cb02c0f0c0c6d1ffaff81d69cec74e.zip | |
examples for MaybeUninit::zeroed
| -rw-r--r-- | src/libcore/mem.rs | 29 |
1 files changed, 29 insertions, 0 deletions
diff --git a/src/libcore/mem.rs b/src/libcore/mem.rs index d586f45534e..8f6798e0f6e 100644 --- a/src/libcore/mem.rs +++ b/src/libcore/mem.rs @@ -1141,6 +1141,35 @@ impl<T> MaybeUninit<T> { /// /// Note that dropping a `MaybeUninit` will never call `T`'s drop code. /// It is your responsibility to make sure `T` gets dropped if it got initialized. + /// + /// # Example + /// + /// Correct usage of this method: initializing a struct with zero, where all + /// fields of the struct can hold 0 as a valid value. + /// + /// ```rust + /// #![feature(maybe_uninit)] + /// use std::mem::MaybeUninit; + /// + /// let x = MaybeUninit::<(u8, bool)>::zeroed(); + /// let x = unsafe { x.into_initialized() }; + /// assert_eq!(x, (0, false)); + /// ``` + /// + /// *Incorrect* usage of this method: initializing a struct with zero, where some fields + /// cannot hold 0 as a valid value. + /// + /// ```rust,no_run + /// #![feature(maybe_uninit)] + /// use std::mem::MaybeUninit; + /// + /// enum NotZero { One = 1, Two = 2 }; + /// + /// let x = MaybeUninit::<(u8, NotZero)>::zeroed(); + /// let x = unsafe { x.into_initialized() }; + /// // We create a `NotZero` (inside a pair) that does not have a valid discriminant. + /// // This is undefined behavior. + /// ``` #[unstable(feature = "maybe_uninit", issue = "53491")] #[inline] pub fn zeroed() -> MaybeUninit<T> { |
