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