]>
git.proxmox.com Git - rustc.git/blob - library/core/src/clone.rs
1 //! The `Clone` trait for types that cannot be 'implicitly copied'.
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.
12 //! [`clone`]: Clone::clone
14 //! Basic usage example:
17 //! let s = String::new(); // String type implements Clone
18 //! let copy = s.clone(); // so we can clone it
21 //! To easily implement the Clone trait, you can also use
22 //! `#[derive(Clone)]`. Example:
25 //! #[derive(Clone)] // we add the Clone trait to Morpheus struct
32 //! let f = Morpheus { blue_pill: 0.0, red_pill: 0 };
33 //! let copy = f.clone(); // and now we can clone it!
37 #![stable(feature = "rust1", since = "1.0.0")]
39 /// A common trait for the ability to explicitly duplicate an object.
41 /// Differs from [`Copy`] in that [`Copy`] is implicit and extremely inexpensive, 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.
46 /// Since `Clone` is more general than [`Copy`], you can automatically make anything
47 /// [`Copy`] be `Clone` as well.
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.
54 /// [`clone`]: Clone::clone
56 /// For a generic struct, `#[derive]` implements `Clone` conditionally by adding bound `Clone` on
57 /// generic parameters.
60 /// // `derive` implements Clone for Reading<T> when T is Clone.
62 /// struct Reading<T> {
67 /// ## How can I implement `Clone`?
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.
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:
78 /// struct Generate<T>(fn() -> T);
80 /// impl<T> Copy for Generate<T> {}
82 /// impl<T> Clone for Generate<T> {
83 /// fn clone(&self) -> Self {
89 /// ## Additional implementors
91 /// In addition to the [implementors listed below][impls],
92 /// the following types also implement `Clone`:
94 /// * Function item types (i.e., the distinct types defined for each function)
95 /// * Function pointer types (e.g., `fn() -> i32`)
96 /// * Array types, for all sizes, if the item type also implements `Clone` (e.g., `[i32; 123456]`)
97 /// * Tuple types, if each component also implements `Clone` (e.g., `()`, `(i32, bool)`)
98 /// * Closure types, if they capture no value from the environment
99 /// or if all such captured values implement `Clone` themselves.
100 /// Note that variables captured by shared reference always implement `Clone`
101 /// (even if the referent doesn't),
102 /// while variables captured by mutable reference never implement `Clone`.
104 /// [impls]: #implementors
105 #[stable(feature = "rust1", since = "1.0.0")]
107 pub trait Clone
: Sized
{
108 /// Returns a copy of the value.
113 /// let hello = "Hello"; // &str implements Clone
115 /// assert_eq!("Hello", hello.clone());
117 #[stable(feature = "rust1", since = "1.0.0")]
118 #[must_use = "cloning is often expensive and is not expected to have side effects"]
119 fn clone(&self) -> Self;
121 /// Performs copy-assignment from `source`.
123 /// `a.clone_from(&b)` is equivalent to `a = b.clone()` in functionality,
124 /// but can be overridden to reuse the resources of `a` to avoid unnecessary
127 #[stable(feature = "rust1", since = "1.0.0")]
128 fn clone_from(&mut self, source
: &Self) {
129 *self = source
.clone()
133 /// Derive macro generating an impl of the trait `Clone`.
134 #[rustc_builtin_macro]
135 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
136 #[allow_internal_unstable(core_intrinsics, derive_clone_copy)]
137 pub macro Clone($item
:item
) {
138 /* compiler built-in */
141 // FIXME(aburka): these structs are used solely by #[derive] to
142 // assert that every component of a type implements Clone or Copy.
144 // These structs should never appear in user code.
146 #[allow(missing_debug_implementations)]
148 feature
= "derive_clone_copy",
149 reason
= "deriving hack, should not be public",
152 pub struct AssertParamIsClone
<T
: Clone
+ ?Sized
> {
153 _field
: crate::marker
::PhantomData
<T
>,
156 #[allow(missing_debug_implementations)]
158 feature
= "derive_clone_copy",
159 reason
= "deriving hack, should not be public",
162 pub struct AssertParamIsCopy
<T
: Copy
+ ?Sized
> {
163 _field
: crate::marker
::PhantomData
<T
>,
166 /// Implementations of `Clone` for primitive types.
168 /// Implementations that cannot be described in Rust
169 /// are implemented in `traits::SelectionContext::copy_clone_conditions()`
170 /// in `rustc_trait_selection`.
175 macro_rules
! impl_clone
{
178 #[stable(feature = "rust1", since = "1.0.0")]
181 fn clone(&self) -> Self {
190 usize u8 u16 u32 u64 u128
191 isize i8 i16 i32 i64 i128
196 #[unstable(feature = "never_type", issue = "35121")]
199 fn clone(&self) -> Self {
204 #[stable(feature = "rust1", since = "1.0.0")]
205 impl<T
: ?Sized
> Clone
for *const T
{
207 fn clone(&self) -> Self {
212 #[stable(feature = "rust1", since = "1.0.0")]
213 impl<T
: ?Sized
> Clone
for *mut T
{
215 fn clone(&self) -> Self {
220 /// Shared references can be cloned, but mutable references *cannot*!
221 #[stable(feature = "rust1", since = "1.0.0")]
222 impl<T
: ?Sized
> Clone
for &T
{
224 fn clone(&self) -> Self {
229 /// Shared references can be cloned, but mutable references *cannot*!
230 #[stable(feature = "rust1", since = "1.0.0")]
231 impl<T
: ?Sized
> !Clone
for &mut T {}