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/// If we `derive`:
90///
91/// ```
92/// #[derive(Copy, Clone)]
93/// struct Generate<T>(fn() -> T);
94/// ```
95///
96/// the auto-derived implementations will have unnecessary `T: Copy` and `T: Clone` bounds:
97///
98/// ```
99/// # struct Generate<T>(fn() -> T);
100///
101/// // Automatically derived
102/// impl<T: Copy> Copy for Generate<T> { }
103///
104/// // Automatically derived
105/// impl<T: Clone> Clone for Generate<T> {
106/// fn clone(&self) -> Generate<T> {
107/// Generate(Clone::clone(&self.0))
108/// }
109/// }
110/// ```
111///
112/// The bounds are unnecessary because clearly the function itself should be
113/// copy- and cloneable even if its return type is not:
114///
115/// ```compile_fail,E0599
116/// #[derive(Copy, Clone)]
117/// struct Generate<T>(fn() -> T);
118///
119/// struct NotCloneable;
120///
121/// fn generate_not_cloneable() -> NotCloneable {
122/// NotCloneable
123/// }
124///
125/// Generate(generate_not_cloneable).clone(); // error: trait bounds were not satisfied
126/// // Note: With the manual implementations the above line will compile.
127/// ```
128///
129/// ## Additional implementors
130///
131/// In addition to the [implementors listed below][impls],
132/// the following types also implement `Clone`:
133///
134/// * Function item types (i.e., the distinct types defined for each function)
135/// * Function pointer types (e.g., `fn() -> i32`)
136/// * Closure types, if they capture no value from the environment
137/// or if all such captured values implement `Clone` themselves.
138/// Note that variables captured by shared reference always implement `Clone`
139/// (even if the referent doesn't),
140/// while variables captured by mutable reference never implement `Clone`.
141///
142/// [impls]: #implementors
143#[stable(feature = "rust1", since = "1.0.0")]
144#[lang = "clone"]
145#[rustc_diagnostic_item = "Clone"]
146#[rustc_trivial_field_reads]
147pub trait Clone: Sized {
148 /// Returns a copy of the value.
149 ///
150 /// # Examples
151 ///
152 /// ```
153 /// # #![allow(noop_method_call)]
154 /// let hello = "Hello"; // &str implements Clone
155 ///
156 /// assert_eq!("Hello", hello.clone());
157 /// ```
158 #[stable(feature = "rust1", since = "1.0.0")]
159 #[must_use = "cloning is often expensive and is not expected to have side effects"]
160 fn clone(&self) -> Self;
161
162 /// Performs copy-assignment from `source`.
163 ///
164 /// `a.clone_from(&b)` is equivalent to `a = b.clone()` in functionality,
165 /// but can be overridden to reuse the resources of `a` to avoid unnecessary
166 /// allocations.
167 #[inline]
168 #[stable(feature = "rust1", since = "1.0.0")]
169 fn clone_from(&mut self, source: &Self) {
170 *self = source.clone()
171 }
172}
173
174/// Derive macro generating an impl of the trait `Clone`.
175#[rustc_builtin_macro]
176#[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
177#[allow_internal_unstable(core_intrinsics, derive_clone_copy)]
178pub macro Clone($item:item) {
179 /* compiler built-in */
180}
181
182// FIXME(aburka): these structs are used solely by #[derive] to
183// assert that every component of a type implements Clone or Copy.
184//
185// These structs should never appear in user code.
186#[doc(hidden)]
187#[allow(missing_debug_implementations)]
188#[unstable(
189 feature = "derive_clone_copy",
190 reason = "deriving hack, should not be public",
191 issue = "none"
192)]
193pub struct AssertParamIsClone<T: Clone + ?Sized> {
194 _field: crate::marker::PhantomData<T>,
195}
196#[doc(hidden)]
197#[allow(missing_debug_implementations)]
198#[unstable(
199 feature = "derive_clone_copy",
200 reason = "deriving hack, should not be public",
201 issue = "none"
202)]
203pub struct AssertParamIsCopy<T: Copy + ?Sized> {
204 _field: crate::marker::PhantomData<T>,
205}
206
207/// Implementations of `Clone` for primitive types.
208///
209/// Implementations that cannot be described in Rust
210/// are implemented in `traits::SelectionContext::copy_clone_conditions()`
211/// in `rustc_trait_selection`.
212mod impls {
213 macro_rules! impl_clone {
214 ($($t:ty)*) => {
215 $(
216 #[stable(feature = "rust1", since = "1.0.0")]
217 impl Clone for $t {
218 #[inline(always)]
219 fn clone(&self) -> Self {
220 *self
221 }
222 }
223 )*
224 }
225 }
226
227 impl_clone! {
228 usize u8 u16 u32 u64 u128
229 isize i8 i16 i32 i64 i128
230 f16 f32 f64 f128
231 bool char
232 }
233
234 #[unstable(feature = "never_type", issue = "35121")]
235 impl Clone for ! {
236 #[inline]
237 fn clone(&self) -> Self {
238 *self
239 }
240 }
241
242 #[stable(feature = "rust1", since = "1.0.0")]
243 impl<T: ?Sized> Clone for *const T {
244 #[inline(always)]
245 fn clone(&self) -> Self {
246 *self
247 }
248 }
249
250 #[stable(feature = "rust1", since = "1.0.0")]
251 impl<T: ?Sized> Clone for *mut T {
252 #[inline(always)]
253 fn clone(&self) -> Self {
254 *self
255 }
256 }
257
258 /// Shared references can be cloned, but mutable references *cannot*!
259 #[stable(feature = "rust1", since = "1.0.0")]
260 impl<T: ?Sized> Clone for &T {
261 #[inline(always)]
262 #[rustc_diagnostic_item = "noop_method_clone"]
263 fn clone(&self) -> Self {
264 *self
265 }
266 }
267
268 /// Shared references can be cloned, but mutable references *cannot*!
269 #[stable(feature = "rust1", since = "1.0.0")]
270 impl<T: ?Sized> !Clone for &mut T {}
271}
272