]> git.lizzy.rs Git - rust.git/blob - src/libcore/clone.rs
46bb580dcddb1af2d8e80152be0a5ccca040b0ac
[rust.git] / src / libcore / clone.rs
1 // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! The `Clone` trait for types that cannot be 'implicitly copied'.
12 //!
13 //! In Rust, some simple types are "implicitly copyable" and when you
14 //! assign them or pass them as arguments, the receiver will get a copy,
15 //! leaving the original value in place. These types do not require
16 //! allocation to copy and do not have finalizers (i.e. they do not
17 //! contain owned boxes or implement [`Drop`]), so the compiler considers
18 //! them cheap and safe to copy. For other types copies must be made
19 //! explicitly, by convention implementing the [`Clone`] trait and calling
20 //! the [`clone`][clone] method.
21 //!
22 //! [`Clone`]: trait.Clone.html
23 //! [clone]: trait.Clone.html#tymethod.clone
24 //! [`Drop`]: ../../std/ops/trait.Drop.html
25 //!
26 //! Basic usage example:
27 //!
28 //! ```
29 //! let s = String::new(); // String type implements Clone
30 //! let copy = s.clone(); // so we can clone it
31 //! ```
32 //!
33 //! To easily implement the Clone trait, you can also use
34 //! `#[derive(Clone)]`. Example:
35 //!
36 //! ```
37 //! #[derive(Clone)] // we add the Clone trait to Morpheus struct
38 //! struct Morpheus {
39 //!    blue_pill: f32,
40 //!    red_pill: i64,
41 //! }
42 //!
43 //! fn main() {
44 //!    let f = Morpheus { blue_pill: 0.0, red_pill: 0 };
45 //!    let copy = f.clone(); // and now we can clone it!
46 //! }
47 //! ```
48
49 #![stable(feature = "rust1", since = "1.0.0")]
50
51 /// A common trait for the ability to explicitly duplicate an object.
52 ///
53 /// Differs from [`Copy`] in that [`Copy`] is implicit and extremely inexpensive, while
54 /// `Clone` is always explicit and may or may not be expensive. In order to enforce
55 /// these characteristics, Rust does not allow you to reimplement [`Copy`], but you
56 /// may reimplement `Clone` and run arbitrary code.
57 ///
58 /// Since `Clone` is more general than [`Copy`], you can automatically make anything
59 /// [`Copy`] be `Clone` as well.
60 ///
61 /// ## Derivable
62 ///
63 /// This trait can be used with `#[derive]` if all fields are `Clone`. The `derive`d
64 /// implementation of [`clone`] calls [`clone`] on each field.
65 ///
66 /// ## How can I implement `Clone`?
67 ///
68 /// Types that are [`Copy`] should have a trivial implementation of `Clone`. More formally:
69 /// if `T: Copy`, `x: T`, and `y: &T`, then `let x = y.clone();` is equivalent to `let x = *y;`.
70 /// Manual implementations should be careful to uphold this invariant; however, unsafe code
71 /// must not rely on it to ensure memory safety.
72 ///
73 /// An example is an array holding more than 32 elements of a type that is `Clone`; the standard
74 /// library only implements `Clone` up until arrays of size 32. In this case, the implementation of
75 /// `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 /// #[derive(Copy)]
82 /// struct Stats {
83 ///    frequencies: [i32; 100],
84 /// }
85 ///
86 /// impl Clone for Stats {
87 ///     fn clone(&self) -> Stats { *self }
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 /// * Array types, for all sizes, if the item type also implements `Clone` (e.g. `[i32; 123456]`)
99 /// * Tuple types, if each component also implements `Clone` (e.g. `()`, `(i32, bool)`)
100 /// * Closure types, if they capture no value from the environment
101 ///   or if all such captured values implement `Clone` themselves.
102 ///   Note that variables captured by shared reference always implement `Clone`
103 ///   (even if the referent doesn't),
104 ///   while variables captured by mutable reference never implement `Clone`.
105 ///
106 /// [impls]: #implementors
107 #[stable(feature = "rust1", since = "1.0.0")]
108 #[lang = "clone"]
109 pub trait Clone : Sized {
110     /// Returns a copy of the value.
111     ///
112     /// # Examples
113     ///
114     /// ```
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     fn clone_from(&mut self, source: &Self) {
131         *self = source.clone()
132     }
133 }
134
135 // FIXME(aburka): these structs are used solely by #[derive] to
136 // assert that every component of a type implements Clone or Copy.
137 //
138 // These structs should never appear in user code.
139 #[doc(hidden)]
140 #[allow(missing_debug_implementations)]
141 #[unstable(feature = "derive_clone_copy",
142            reason = "deriving hack, should not be public",
143            issue = "0")]
144 pub struct AssertParamIsClone<T: Clone + ?Sized> { _field: ::marker::PhantomData<T> }
145 #[doc(hidden)]
146 #[allow(missing_debug_implementations)]
147 #[unstable(feature = "derive_clone_copy",
148            reason = "deriving hack, should not be public",
149            issue = "0")]
150 pub struct AssertParamIsCopy<T: Copy + ?Sized> { _field: ::marker::PhantomData<T> }
151
152 /// Implementations of `Clone` for primitive types.
153 ///
154 /// Implementations that cannot be described in Rust
155 /// are implemented in `SelectionContext::copy_clone_conditions()` in librustc.
156 mod impls {
157
158     use super::Clone;
159
160     macro_rules! impl_clone {
161         ($($t:ty)*) => {
162             $(
163                 #[stable(feature = "rust1", since = "1.0.0")]
164                 impl Clone for $t {
165                     #[inline]
166                     fn clone(&self) -> Self {
167                         *self
168                     }
169                 }
170             )*
171         }
172     }
173
174     impl_clone! {
175         usize u8 u16 u32 u64 u128
176         isize i8 i16 i32 i64 i128
177         f32 f64
178         bool char
179     }
180
181     #[unstable(feature = "never_type", issue = "35121")]
182     impl Clone for ! {
183         #[inline]
184         fn clone(&self) -> Self {
185             *self
186         }
187     }
188
189     #[stable(feature = "rust1", since = "1.0.0")]
190     impl<T: ?Sized> Clone for *const T {
191         #[inline]
192         fn clone(&self) -> Self {
193             *self
194         }
195     }
196
197     #[stable(feature = "rust1", since = "1.0.0")]
198     impl<T: ?Sized> Clone for *mut T {
199         #[inline]
200         fn clone(&self) -> Self {
201             *self
202         }
203     }
204
205     // Shared references can be cloned, but mutable references *cannot*!
206     #[stable(feature = "rust1", since = "1.0.0")]
207     impl<T: ?Sized> Clone for &T {
208         #[inline]
209         fn clone(&self) -> Self {
210             *self
211         }
212     }
213
214 }