pub trait Clone: Sized {
// Required method
fn clone(&self) -> Self;
// Provided method
fn clone_from(&mut self, source: &Self) { ... }
}
Expand description
A common trait that allows explicit creation of a duplicate value.
Calling clone
always produces a new value. However, for types that are references to other data (such as smart pointers or references), the new value may still point to the same underlying data, rather than duplicating it. See Clone::clone
for more details.
This distinction is especially important when using #[derive(Clone)]
on structs containing smart pointers like Arc<Mutex<T>>
- the cloned struct will share mutable state with the original.
Differs from Copy
in that Copy
is implicit and an inexpensive bit-wise copy, while Clone
is always explicit and may or may not be expensive. In order to enforce these characteristics, Rust does not allow you to reimplement Copy
, but you may reimplement Clone
and run arbitrary code.
Since Clone
is more general than Copy
, you can automatically make anything Copy
be Clone
as well.
This trait can be used with #[derive]
if all fields are Clone
. The derive
d implementation of Clone
calls clone
on each field.
For a generic struct, #[derive]
implements Clone
conditionally by adding bound Clone
on generic parameters.
#[derive(Clone)]
struct Reading<T> {
frequency: T,
}
§How can I implement Clone
?
Types that are Copy
should have a trivial implementation of Clone
. More formally: if T: Copy
, x: T
, and y: &T
, then let x = y.clone();
is equivalent to let x = *y;
. Manual implementations should be careful to uphold this invariant; however, unsafe code must not rely on it to ensure memory safety.
An example is a generic struct holding a function pointer. In this case, the implementation of Clone
cannot be derive
d, but can be implemented as:
struct Generate<T>(fn() -> T);
impl<T> Copy for Generate<T> {}
impl<T> Clone for Generate<T> {
fn clone(&self) -> Self {
*self
}
}
If we derive
:
#[derive(Copy, Clone)]
struct Generate<T>(fn() -> T);
the auto-derived implementations will have unnecessary T: Copy
and T: Clone
bounds:
impl<T: Copy> Copy for Generate<T> { }
impl<T: Clone> Clone for Generate<T> {
fn clone(&self) -> Generate<T> {
Generate(Clone::clone(&self.0))
}
}
The bounds are unnecessary because clearly the function itself should be copy- and cloneable even if its return type is not:
â#[derive(Copy, Clone)]
struct Generate<T>(fn() -> T);
struct NotCloneable;
fn generate_not_cloneable() -> NotCloneable {
NotCloneable
}
Generate(generate_not_cloneable).clone();
§Clone
and PartialEq
/Eq
Clone
is intended for the duplication of objects. Consequently, when implementing both Clone
and PartialEq
, the following property is expected to hold:
In other words, if an object compares equal to itself, its clone must also compare equal to the original.
For types that also implement Eq
â for which x == x
always holds â this implies that x.clone() == x
must always be true. Standard library collections such as HashMap
, HashSet
, BTreeMap
, BTreeSet
and BinaryHeap
rely on their keys respecting this property for correct behavior. Furthermore, these collections require that cloning a key preserves the outcome of the Hash
and Ord
methods. Thankfully, this follows automatically from x.clone() == x
if Hash
and Ord
are correctly implemented according to their own requirements.
When deriving both Clone
and PartialEq
using #[derive(Clone, PartialEq)]
or when additionally deriving Eq
using #[derive(Clone, PartialEq, Eq)]
, then this property is automatically upheld â provided that it is satisfied by the underlying types.
Violating this property is a logic error. The behavior resulting from a logic error is not specified, but users of the trait must ensure that such logic errors do not result in undefined behavior. This means that unsafe
code must not rely on this property being satisfied.
In addition to the implementors listed below, the following types also implement Clone
:
fn() -> i32
)Clone
themselves. Note that variables captured by shared reference always implement Clone
(even if the referent doesnât), while variables captured by mutable reference never implement Clone
.Returns a duplicate of the value.
Note that what âduplicateâ means varies by type:
&T
, this creates another reference to the same valueArc
or Rc
, this increments the reference count but still points to the same underlying datalet hello = "Hello"; assert_eq!("Hello", hello.clone());
Example with a reference-counted type:
use std::sync::{Arc, Mutex};
let data = Arc::new(Mutex::new(vec![1, 2, 3]));
let data_clone = data.clone(); {
let mut lock = data.lock().unwrap();
lock.push(4);
}
assert_eq!(*data_clone.lock().unwrap(), vec![1, 2, 3, 4]);
1.0.0 · Source
Performs copy-assignment from source
.
a.clone_from(&b)
is equivalent to a = b.clone()
in functionality, but can be overridden to reuse the resources of a
to avoid unnecessary allocations.
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4