]> git.lizzy.rs Git - rust.git/blob - library/core/src/clone.rs
Rollup merge of #95553 - jam1garner:naked-function-compile-error, r=tmiasko
[rust.git] / library / core / src / clone.rs
1 //! The `Clone` trait for types that cannot be 'implicitly copied'.
2 //!
3 //! In Rust, some simple types are "implicitly copyable" and when you
4 //! assign them or pass them as arguments, the receiver will get a copy,
5 //! leaving the original value in place. These types do not require
6 //! allocation to copy and do not have finalizers (i.e., they do not
7 //! contain owned boxes or implement [`Drop`]), so the compiler considers
8 //! them cheap and safe to copy. For other types copies must be made
9 //! explicitly, by convention implementing the [`Clone`] trait and calling
10 //! the [`clone`] method.
11 //!
12 //! [`clone`]: Clone::clone
13 //!
14 //! Basic usage example:
15 //!
16 //! ```
17 //! let s = String::new(); // String type implements Clone
18 //! let copy = s.clone(); // so we can clone it
19 //! ```
20 //!
21 //! To easily implement the Clone trait, you can also use
22 //! `#[derive(Clone)]`. Example:
23 //!
24 //! ```
25 //! #[derive(Clone)] // we add the Clone trait to Morpheus struct
26 //! struct Morpheus {
27 //!    blue_pill: f32,
28 //!    red_pill: i64,
29 //! }
30 //!
31 //! fn main() {
32 //!    let f = Morpheus { blue_pill: 0.0, red_pill: 0 };
33 //!    let copy = f.clone(); // and now we can clone it!
34 //! }
35 //! ```
36
37 #![stable(feature = "rust1", since = "1.0.0")]
38
39 use crate::marker::Destruct;
40
41 /// A common trait for the ability to explicitly duplicate an object.
42 ///
43 /// Differs from [`Copy`] in that [`Copy`] is implicit and an inexpensive bit-wise copy, while
44 /// `Clone` is always explicit and may or may not be expensive. In order to enforce
45 /// these characteristics, Rust does not allow you to reimplement [`Copy`], but you
46 /// may reimplement `Clone` and run arbitrary code.
47 ///
48 /// Since `Clone` is more general than [`Copy`], you can automatically make anything
49 /// [`Copy`] be `Clone` as well.
50 ///
51 /// ## Derivable
52 ///
53 /// This trait can be used with `#[derive]` if all fields are `Clone`. The `derive`d
54 /// implementation of [`Clone`] calls [`clone`] on each field.
55 ///
56 /// [`clone`]: Clone::clone
57 ///
58 /// For a generic struct, `#[derive]` implements `Clone` conditionally by adding bound `Clone` on
59 /// generic parameters.
60 ///
61 /// ```
62 /// // `derive` implements Clone for Reading<T> when T is Clone.
63 /// #[derive(Clone)]
64 /// struct Reading<T> {
65 ///     frequency: T,
66 /// }
67 /// ```
68 ///
69 /// ## How can I implement `Clone`?
70 ///
71 /// Types that are [`Copy`] should have a trivial implementation of `Clone`. More formally:
72 /// if `T: Copy`, `x: T`, and `y: &T`, then `let x = y.clone();` is equivalent to `let x = *y;`.
73 /// Manual implementations should be careful to uphold this invariant; however, unsafe code
74 /// must not rely on it to ensure memory safety.
75 ///
76 /// An example is a generic struct holding a function pointer. In this case, the
77 /// implementation of `Clone` cannot be `derive`d, but can be implemented as:
78 ///
79 /// ```
80 /// struct Generate<T>(fn() -> T);
81 ///
82 /// impl<T> Copy for Generate<T> {}
83 ///
84 /// impl<T> Clone for Generate<T> {
85 ///     fn clone(&self) -> Self {
86 ///         *self
87 ///     }
88 /// }
89 /// ```
90 ///
91 /// ## Additional implementors
92 ///
93 /// In addition to the [implementors listed below][impls],
94 /// the following types also implement `Clone`:
95 ///
96 /// * Function item types (i.e., the distinct types defined for each function)
97 /// * Function pointer types (e.g., `fn() -> i32`)
98 /// * Tuple types, if each component also implements `Clone` (e.g., `()`, `(i32, bool)`)
99 /// * Closure types, if they capture no value from the environment
100 ///   or if all such captured values implement `Clone` themselves.
101 ///   Note that variables captured by shared reference always implement `Clone`
102 ///   (even if the referent doesn't),
103 ///   while variables captured by mutable reference never implement `Clone`.
104 ///
105 /// [impls]: #implementors
106 #[stable(feature = "rust1", since = "1.0.0")]
107 #[lang = "clone"]
108 #[rustc_diagnostic_item = "Clone"]
109 #[rustc_trivial_field_reads]
110 pub trait Clone: Sized {
111     /// Returns a copy of the value.
112     ///
113     /// # Examples
114     ///
115     /// ```
116     /// # #![allow(noop_method_call)]
117     /// let hello = "Hello"; // &str implements Clone
118     ///
119     /// assert_eq!("Hello", hello.clone());
120     /// ```
121     #[stable(feature = "rust1", since = "1.0.0")]
122     #[must_use = "cloning is often expensive and is not expected to have side effects"]
123     fn clone(&self) -> Self;
124
125     /// Performs copy-assignment from `source`.
126     ///
127     /// `a.clone_from(&b)` is equivalent to `a = b.clone()` in functionality,
128     /// but can be overridden to reuse the resources of `a` to avoid unnecessary
129     /// allocations.
130     #[inline]
131     #[stable(feature = "rust1", since = "1.0.0")]
132     #[default_method_body_is_const]
133     #[cfg_attr(not(bootstrap), allow(drop_bounds))] // FIXME remove `~const Drop` and this attr when bumping
134     fn clone_from(&mut self, source: &Self)
135     where
136         Self: ~const Drop + ~const Destruct,
137     {
138         *self = source.clone()
139     }
140 }
141
142 /// Derive macro generating an impl of the trait `Clone`.
143 #[rustc_builtin_macro]
144 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
145 #[allow_internal_unstable(core_intrinsics, derive_clone_copy)]
146 pub macro Clone($item:item) {
147     /* compiler built-in */
148 }
149
150 // FIXME(aburka): these structs are used solely by #[derive] to
151 // assert that every component of a type implements Clone or Copy.
152 //
153 // These structs should never appear in user code.
154 #[doc(hidden)]
155 #[allow(missing_debug_implementations)]
156 #[unstable(
157     feature = "derive_clone_copy",
158     reason = "deriving hack, should not be public",
159     issue = "none"
160 )]
161 pub struct AssertParamIsClone<T: Clone + ?Sized> {
162     _field: crate::marker::PhantomData<T>,
163 }
164 #[doc(hidden)]
165 #[allow(missing_debug_implementations)]
166 #[unstable(
167     feature = "derive_clone_copy",
168     reason = "deriving hack, should not be public",
169     issue = "none"
170 )]
171 pub struct AssertParamIsCopy<T: Copy + ?Sized> {
172     _field: crate::marker::PhantomData<T>,
173 }
174
175 /// Implementations of `Clone` for primitive types.
176 ///
177 /// Implementations that cannot be described in Rust
178 /// are implemented in `traits::SelectionContext::copy_clone_conditions()`
179 /// in `rustc_trait_selection`.
180 mod impls {
181
182     use super::Clone;
183
184     macro_rules! impl_clone {
185         ($($t:ty)*) => {
186             $(
187                 #[stable(feature = "rust1", since = "1.0.0")]
188                 #[rustc_const_unstable(feature = "const_clone", issue = "91805")]
189                 impl const Clone for $t {
190                     #[inline]
191                     fn clone(&self) -> Self {
192                         *self
193                     }
194                 }
195             )*
196         }
197     }
198
199     impl_clone! {
200         usize u8 u16 u32 u64 u128
201         isize i8 i16 i32 i64 i128
202         f32 f64
203         bool char
204     }
205
206     #[unstable(feature = "never_type", issue = "35121")]
207     #[rustc_const_unstable(feature = "const_clone", issue = "91805")]
208     impl const Clone for ! {
209         #[inline]
210         fn clone(&self) -> Self {
211             *self
212         }
213     }
214
215     #[stable(feature = "rust1", since = "1.0.0")]
216     #[rustc_const_unstable(feature = "const_clone", issue = "91805")]
217     impl<T: ?Sized> const Clone for *const T {
218         #[inline]
219         fn clone(&self) -> Self {
220             *self
221         }
222     }
223
224     #[stable(feature = "rust1", since = "1.0.0")]
225     #[rustc_const_unstable(feature = "const_clone", issue = "91805")]
226     impl<T: ?Sized> const Clone for *mut T {
227         #[inline]
228         fn clone(&self) -> Self {
229             *self
230         }
231     }
232
233     /// Shared references can be cloned, but mutable references *cannot*!
234     #[stable(feature = "rust1", since = "1.0.0")]
235     #[rustc_const_unstable(feature = "const_clone", issue = "91805")]
236     impl<T: ?Sized> const Clone for &T {
237         #[inline]
238         #[rustc_diagnostic_item = "noop_method_clone"]
239         fn clone(&self) -> Self {
240             *self
241         }
242     }
243
244     /// Shared references can be cloned, but mutable references *cannot*!
245     #[stable(feature = "rust1", since = "1.0.0")]
246     impl<T: ?Sized> !Clone for &mut T {}
247 }