]> git.lizzy.rs Git - rust.git/blob - src/libcore/clone.rs
Rollup merge of #66330 - Nadrieril:nonexhaustive-constructor, r=varkor
[rust.git] / src / libcore / 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`][clone] method.
11 //!
12 //! [`Clone`]: trait.Clone.html
13 //! [clone]: trait.Clone.html#tymethod.clone
14 //! [`Drop`]: ../../std/ops/trait.Drop.html
15 //!
16 //! Basic usage example:
17 //!
18 //! ```
19 //! let s = String::new(); // String type implements Clone
20 //! let copy = s.clone(); // so we can clone it
21 //! ```
22 //!
23 //! To easily implement the Clone trait, you can also use
24 //! `#[derive(Clone)]`. Example:
25 //!
26 //! ```
27 //! #[derive(Clone)] // we add the Clone trait to Morpheus struct
28 //! struct Morpheus {
29 //!    blue_pill: f32,
30 //!    red_pill: i64,
31 //! }
32 //!
33 //! fn main() {
34 //!    let f = Morpheus { blue_pill: 0.0, red_pill: 0 };
35 //!    let copy = f.clone(); // and now we can clone it!
36 //! }
37 //! ```
38
39 #![stable(feature = "rust1", since = "1.0.0")]
40
41 /// A common trait for the ability to explicitly duplicate an object.
42 ///
43 /// Differs from [`Copy`] in that [`Copy`] is implicit and extremely inexpensive, 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 /// 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 /// [`Copy`]: ../../std/marker/trait.Copy.html
78 /// [`clone`]: trait.Clone.html#tymethod.clone
79 ///
80 /// ```
81 /// struct Generate<T>(fn() -> T);
82 ///
83 /// impl<T> Copy for Generate<T> {}
84 ///
85 /// impl<T> Clone for Generate<T> {
86 ///     fn clone(&self) -> Self {
87 ///         *self
88 ///     }
89 /// }
90 /// ```
91 ///
92 /// ## Additional implementors
93 ///
94 /// In addition to the [implementors listed below][impls],
95 /// the following types also implement `Clone`:
96 ///
97 /// * Function item types (i.e., the distinct types defined for each function)
98 /// * Function pointer types (e.g., `fn() -> i32`)
99 /// * Array types, for all sizes, if the item type also implements `Clone` (e.g., `[i32; 123456]`)
100 /// * Tuple types, if each component also implements `Clone` (e.g., `()`, `(i32, bool)`)
101 /// * Closure types, if they capture no value from the environment
102 ///   or if all such captured values implement `Clone` themselves.
103 ///   Note that variables captured by shared reference always implement `Clone`
104 ///   (even if the referent doesn't),
105 ///   while variables captured by mutable reference never implement `Clone`.
106 ///
107 /// [impls]: #implementors
108 #[stable(feature = "rust1", since = "1.0.0")]
109 #[lang = "clone"]
110 pub trait Clone : Sized {
111     /// Returns a copy of the value.
112     ///
113     /// # Examples
114     ///
115     /// ```
116     /// let hello = "Hello"; // &str implements Clone
117     ///
118     /// assert_eq!("Hello", hello.clone());
119     /// ```
120     #[stable(feature = "rust1", since = "1.0.0")]
121     #[must_use = "cloning is often expensive and is not expected to have side effects"]
122     fn clone(&self) -> Self;
123
124     /// Performs copy-assignment from `source`.
125     ///
126     /// `a.clone_from(&b)` is equivalent to `a = b.clone()` in functionality,
127     /// but can be overridden to reuse the resources of `a` to avoid unnecessary
128     /// allocations.
129     #[inline]
130     #[stable(feature = "rust1", since = "1.0.0")]
131     fn clone_from(&mut self, source: &Self) {
132         *self = source.clone()
133     }
134 }
135
136 /// Derive macro generating an impl of the trait `Clone`.
137 #[rustc_builtin_macro]
138 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
139 #[allow_internal_unstable(core_intrinsics, derive_clone_copy)]
140 pub macro Clone($item:item) { /* compiler built-in */ }
141
142 // FIXME(aburka): these structs are used solely by #[derive] to
143 // assert that every component of a type implements Clone or Copy.
144 //
145 // These structs should never appear in user code.
146 #[doc(hidden)]
147 #[allow(missing_debug_implementations)]
148 #[unstable(feature = "derive_clone_copy",
149            reason = "deriving hack, should not be public",
150            issue = "0")]
151 pub struct AssertParamIsClone<T: Clone + ?Sized> { _field: crate::marker::PhantomData<T> }
152 #[doc(hidden)]
153 #[allow(missing_debug_implementations)]
154 #[unstable(feature = "derive_clone_copy",
155            reason = "deriving hack, should not be public",
156            issue = "0")]
157 pub struct AssertParamIsCopy<T: Copy + ?Sized> { _field: crate::marker::PhantomData<T> }
158
159 /// Implementations of `Clone` for primitive types.
160 ///
161 /// Implementations that cannot be described in Rust
162 /// are implemented in `SelectionContext::copy_clone_conditions()` in librustc.
163 mod impls {
164
165     use super::Clone;
166
167     macro_rules! impl_clone {
168         ($($t:ty)*) => {
169             $(
170                 #[stable(feature = "rust1", since = "1.0.0")]
171                 impl Clone for $t {
172                     #[inline]
173                     fn clone(&self) -> Self {
174                         *self
175                     }
176                 }
177             )*
178         }
179     }
180
181     impl_clone! {
182         usize u8 u16 u32 u64 u128
183         isize i8 i16 i32 i64 i128
184         f32 f64
185         bool char
186     }
187
188     #[unstable(feature = "never_type", issue = "35121")]
189     impl Clone for ! {
190         #[inline]
191         fn clone(&self) -> Self {
192             *self
193         }
194     }
195
196     #[stable(feature = "rust1", since = "1.0.0")]
197     impl<T: ?Sized> Clone for *const T {
198         #[inline]
199         fn clone(&self) -> Self {
200             *self
201         }
202     }
203
204     #[stable(feature = "rust1", since = "1.0.0")]
205     impl<T: ?Sized> Clone for *mut T {
206         #[inline]
207         fn clone(&self) -> Self {
208             *self
209         }
210     }
211
212     // Shared references can be cloned, but mutable references *cannot*!
213     #[stable(feature = "rust1", since = "1.0.0")]
214     impl<T: ?Sized> Clone for &T {
215         #[inline]
216         fn clone(&self) -> Self {
217             *self
218         }
219     }
220
221 }