Text of rust.docs.kernel.org › src › core › mem › mod.rs.html as Styx crawled it on Nov 20, 2026. The page may have changed since. Only its words are kept, without pictures or layout, and only the first part of a long page.

Open the live page

mod.rs - source

Skip to main content core/mem/ mod.rs 1 //! Basic functions for dealing with memory, values, and types. 2 //! 3 //! The contents of this module can be seen as belonging to a few families: 4 //! 5 //! * [`drop`], [`replace`], [`swap`], and [`take`] 6 //! are safe functions for moving values in particular ways. 7 //! They are useful in everyday Rust code. 8 //! 9 //! * [`size_of`], [`size_of_val`], [`align_of`], [`align_of_val`], and [`offset_of`] 10 //! give information about the representation of values in memory.

11 //! 12 //! * [`discriminant`] 13 //! allows comparing the variants of [`enum`] values while ignoring their fields. 14 //! 15 //! * [`forget`] and [`ManuallyDrop`] 16 //! prevent destructors from running, which is used in certain kinds of ownership transfer. 17 //! [`needs_drop`] 18 //! tells you whether a type’s destructor even does anything. 19 //! 20 //! * [`transmute`], [`transmute_copy`], and [`MaybeUninit`] 21 //! convert and construct values in [`unsafe`] ways.

22 //! 23 //! See also the [`alloc`] and [`ptr`] modules for more primitive operations on memory. 24 //! 25 // core::alloc exists but doesn’t contain all the items we want to discuss 26 //! [`alloc`]: ../../std/alloc/index.html 27 //! [`enum`]: ../../std/keyword.enum.html 28 //! [`ptr`]: crate::ptr 29 //! [`unsafe`]: ../../std/keyword.unsafe.html 30 31 #![stable(feature = "rust1" , since = "1.0.0" )] 32 33 use crate ::alloc::Layout ; 34 use crate ::clone::TrivialClone ; 35 use crate ::cmp::Ordering ; 36 use crate ::marker::{ Destruct , DiscriminantKind }; 37 use crate ::panic::const_assert ; 38 use crate ::ub_checks::assert_unsafe_precondition ; 39 use crate ::{ clone , cmp , fmt , hash , intrinsics , ptr }; 40 41 mod alignment ; 42 #[unstable(feature = "ptr_alignment_type" , issue = "102070" )] 43 pub use alignment::Alignment ; 44 45 mod manually_drop ; 46 #[stable(feature = "manually_drop" , since = "1.20.0" )] 47 pub use manually_drop::ManuallyDrop ; 48 49 mod maybe_uninit ; 50 #[stable(feature = "maybe_uninit" , since = "1.36.0" )] 51 pub use maybe_uninit::MaybeUninit ; 52 53 mod maybe_dangling ; 54 #[unstable(feature = "maybe_dangling" , issue = "118166" )] 55 pub use maybe_dangling::MaybeDangling ; 56 57 mod transmutability ; 58 #[unstable(feature = "transmutability" , issue = "99571" )] 59 pub use transmutability::{ Assume , TransmuteFrom }; 60 61 mod drop_guard ; 62 #[stable(feature = "drop_guard" , since = "1.100.0" )] 63 pub use drop_guard::DropGuard ; 64 65 // This one has to be a re-export (rather than wrapping the underlying intrinsic) so that we can do 66 // the special magic "types have equal size" check at the call site.

67 #[stable(feature = "rust1" , since = "1.0.0" )] 68 #[doc(inline)] 69 pub use crate ::intrinsics::transmute ; 70 71 #[unstable(feature = "type_info" , issue = "146922" )] 72 pub mod type_info ; 73 74 /// Takes ownership and "forgets" about the value **without running its destructor**. 75 /// 76 /// Any resources the value manages, such as heap memory or a file handle, will linger 77 /// forever in an unreachable state.

However, it does not guarantee that pointers 78 /// to this memory will remain valid. 79 /// 80 /// * If you want to leak memory, see [`Box::leak`]. 81 /// * If you want to obtain a raw pointer to the memory, see [`Box::into_raw`]. 82 /// * If you want to dispose of a value properly, running its destructor, see 83 /// [`mem::drop`]. 84 /// 85 /// # Safety 86 /// 87 /// `forget` is not marked as `unsafe`, because Rust's safety guarantees 88 /// do not include a guarantee that destructors will always run.

For example, 89 /// a program can create a reference cycle using [`Rc`][rc], or call 90 /// [`process::exit`][exit] to exit without running destructors. Thus, allowing 91 /// `mem::forget` from safe code does not fundamentally change Rust's safety 92 /// guarantees. 93 /// 94 /// That said, leaking resources such as memory or I/O objects is usually undesirable. 95 /// The need comes up in some specialized use cases for FFI or unsafe code, but even 96 /// then, [`ManuallyDrop`] is typically preferred.

97 /// 98 /// Because forgetting a value is allowed, any `unsafe` code you write must 99 /// allow for this possibility. You cannot return a value and expect that the 100 /// caller will necessarily run the value's destructor. 101 /// 102 /// [rc]: ../../std/rc/struct.Rc.html 103 /// [exit]: ../../std/process/fn.exit.html 104 /// 105 /// # Examples 106 /// 107 /// The canonical safe use of `mem::forget` is to circumvent a value's destructor 108 /// implemented by the `Drop` trait.

For example, this will leak a `File`, i.e. reclaim 109 /// the space taken by the variable but never close the underlying system resource: 110 /// 111 /// ```no_run 112 /// use std::mem; 113 /// use std::fs::File; 114 /// 115 /// let file = File::open("foo.txt").unwrap(); 116 /// mem::forget(file); 117 /// ``` 118 /// 119 /// This is useful when the ownership of the underlying resource was previously 120 /// transferred to code outside of Rust, for example by transmitting the raw 121 /// file descriptor to C code.

122 /// 123 /// # Relationship with `ManuallyDrop` 124 /// 125 /// While `mem::forget` can also be used to transfer *memory* ownership, doing so is error-prone. 126 /// [`ManuallyDrop`] should be used instead. Consider, for example, this code: 127 /// 128 /// ``` 129 /// use std::mem; 130 /// 131 /// let mut v = vec![65, 122]; 132 /// // Build a `String` using the contents of `v` 133 /// let s = unsafe { String::from_raw_parts(v.as_mut_ptr(), v.len(), v.capacity()) }; 134 /// // leak `v` because its memory is now managed by `s` 135 /// mem::forget(v); // ERROR - v is invalid and must not be passed to a function 136 /// assert_eq!(s, "Az"); 137 /// // `s` is implicitly dropped and its memory deallocated.

138 /// ``` 139 /// 140 /// There are two issues with the above example: 141 /// 142 /// * If more code were added between the construction of `String` and the invocation of 143 /// `mem::forget()`, a panic within it would cause a double free because the same memory 144 /// is handled by both `v` and `s`. 145 /// * After calling `v.as_mut_ptr()` and transmitting the ownership of the data to `s`, 146 /// the `v` value is invalid.

Even when a value is just moved to `mem::forget` (which won't 147 /// inspect it), some types have strict requirements on their values that 148 /// make them invalid when dangling or no longer owned. Using invalid values in any 149 /// way, including passing them to or returning them from functions, constitutes 150 /// undefined behavior and may break the assumptions made by the compiler. 151 /// 152 /// Switching to `ManuallyDrop` avoids both issues: 153 /// 154 /// ``` 155 /// use std::mem::ManuallyDrop; 156 /// 157 /// let v = vec![65, 122]; 158 /// // Before we disassemble `v` into its raw parts, make sure it 159 /// // does not get dropped!

160 /// let mut v = ManuallyDrop::new(v); 161 /// // Now disassemble `v`. These operations cannot panic, so there cannot be a leak. 162 /// let (ptr, len, cap) = (v.as_mut_ptr(), v.len(), v.capacity()); 163 /// // Finally, build a `String`. 164 /// let s = unsafe { String::from_raw_parts(ptr, len, cap) }; 165 /// assert_eq!(s, "Az"); 166 /// // `s` is implicitly dropped and its memory deallocated. 167 /// ``` 168 /// 169 /// `ManuallyDrop` robustly prevents double-free because we disable `v`'s destructor 170 /// before doing anything else. `mem::forget()` doesn't allow this because it consumes its 171 /// argument, forcing us to call it only after extracting anything we need from `v`.

Even 172 /// if a panic were introduced between construction of `ManuallyDrop` and building the 173 /// string (which cannot happen in the code as shown), it would result in a leak and not a 174 /// double free. In other words, `ManuallyDrop` errs on the side of leaking instead of 175 /// erring on the side of (double-)dropping. 176 /// 177 /// Also, `ManuallyDrop` prevents us from having to "

The rest of this page is on the live site.