Skip to main content

Clone

Trait Clone 

1.6.0 (const: unstable) · Source
pub trait Clone: Sized {
    // Required method
    fn clone(&self) -> Self;

    // Provided method
    fn clone_from(&mut self, source: &Self)
       where 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. Copy has no methods, so you cannot change its behavior, but when implementing Clone, the clone method you provide may run arbitrary code.

Since Clone is a supertrait of Copy, any type that implements Copy must also implement Clone.

§Derivable

This trait can be used with #[derive] if all fields are Clone. The derived implementation of Clone calls clone on each field.

For a generic struct, #[derive] implements Clone conditionally by adding bound Clone on generic parameters.

// `derive` implements Clone for Reading<T> when T is Clone.
#[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 derived, 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:


// Automatically derived
impl<T: Copy> Copy for Generate<T> { }

// Automatically derived
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(); // error: trait bounds were not satisfied
// Note: With the manual implementations the above line will compile.

§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:

x == x -> x.clone() == x

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.

§Additional implementors

In addition to the implementors listed below, the following types also implement Clone:

  • Function item types (i.e., the distinct types defined for each function)
  • Function pointer types (e.g., fn() -> i32)
  • Closure types, if they capture no value from the environment or if all such captured values implement 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.

Required Methods§

1.0.0 · Source

fn clone(&self) -> Self

Returns a duplicate of the value.

Note that what “duplicate” means varies by type:

  • For most types, this creates a deep, independent copy
  • For reference types like &T, this creates another reference to the same value
  • For smart pointers like Arc or Rc, this increments the reference count but still points to the same underlying data
§Examples
let hello = "Hello"; // &str implements Clone

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(); // Creates another Arc pointing to the same Mutex

{
    let mut lock = data.lock().unwrap();
    lock.push(4);
}

// Changes are visible through the clone because they share the same underlying data
assert_eq!(*data_clone.lock().unwrap(), vec![1, 2, 3, 4]);

Provided Methods§

1.0.0 · Source

fn clone_from(&mut self, source: &Self)
where Self:,

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.

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.

Implementors§

1.0.0 · Source§

impl<T: PointeeSized> !Clone for &mut T

Shared references can be cloned, but mutable references cannot!

Source§

impl Clone for AsciiChar

1.0.0 (const: unstable) · Source§

impl Clone for core::cmp::Ordering

1.34.0 (const: unstable) · Source§

impl Clone for Infallible

1.64.0 · Source§

impl Clone for FromBytesWithNulError

1.28.0 · Source§

impl Clone for core::fmt::Alignment

Source§

impl Clone for DebugAsHex

Source§

impl Clone for Sign

1.0.0 · Source§

impl Clone for FpCategory

1.55.0 · Source§

impl Clone for IntErrorKind

Source§

impl Clone for SearchStep

1.0.0 · Source§

impl Clone for core::sync::atomic::Ordering

1.0.0 (const: unstable) · Source§

impl Clone for bool

1.0.0 (const: unstable) · Source§

impl Clone for char

1.0.0 (const: unstable) · Source§

impl Clone for f16

1.0.0 (const: unstable) · Source§

impl Clone for f32

1.0.0 (const: unstable) · Source§

impl Clone for f64

1.0.0 (const: unstable) · Source§

impl Clone for f128

1.0.0 (const: unstable) · Source§

impl Clone for i8

1.0.0 (const: unstable) · Source§

impl Clone for i16

1.0.0 (const: unstable) · Source§

impl Clone for i32

1.0.0 (const: unstable) · Source§

impl Clone for i64

1.0.0 (const: unstable) · Source§

impl Clone for i128

1.0.0 (const: unstable) · Source§

impl Clone for isize

Source§

impl Clone for !

1.0.0 (const: unstable) · Source§

impl Clone for u8

1.0.0 (const: unstable) · Source§

impl Clone for u16

1.0.0 (const: unstable) · Source§

impl Clone for u32

1.0.0 (const: unstable) · Source§

impl Clone for u64

1.0.0 (const: unstable) · Source§

impl Clone for u128

1.0.0 (const: unstable) · Source§

impl Clone for usize

1.28.0 · Source§

impl Clone for Layout

1.0.0 (const: unstable) · Source§

impl Clone for TypeId

1.95.0 · Source§

impl Clone for float16x4_t

Available on (AArch64 or target_arch=arm64ec or target feature v7) and (ARM or AArch64 or target_arch=arm64ec) only.
1.95.0 · Source§

impl Clone for float16x8_t

Available on (AArch64 or target_arch=arm64ec or target feature v7) and (ARM or AArch64 or target_arch=arm64ec) only.
1.59.0 · Source§

impl Clone for float32x2_t

Available on (AArch64 or target_arch=arm64ec or target feature v7) and (ARM or AArch64 or target_arch=arm64ec) only.
1.59.0 · Source§

impl Clone for float32x2x2_t

Available on (AArch64 or target_arch=arm64ec or target feature v7) and (ARM or AArch64 or target_arch=arm64ec) only.
1.59.0 · Source§

impl Clone for float32x4_t

Available on (AArch64 or target_arch=arm64ec or target feature v7) and (ARM or AArch64 or target_arch=arm64ec) only.
1.59.0 · Source§

impl Clone for float32x4x2_t

Available on (AArch64 or target_arch=arm64ec or target feature v7) and (ARM or AArch64 or target_arch=arm64ec) only.
1.59.0 · Source§

impl Clone for float64x1_t

Available on AArch64 or target_arch=arm64ec only.
1.59.0 · Source§

impl Clone for float64x1x2_t

Available on AArch64 or target_arch=arm64ec only.
1.59.0 · Source§

impl Clone for float64x1x3_t

Available on AArch64 or target_arch=arm64ec only.
1.59.0 · Source§

impl Clone for float64x1x4_t

Available on AArch64 or target_arch=arm64ec only.
1.59.0 · Source§

impl Clone for float64x2_t

Available on AArch64 or target_arch=arm64ec only.
1.59.0 · Source§

impl Clone for float64x2x2_t

Available on AArch64 or target_arch=arm64ec only.
1.59.0 · Source§

impl Clone for float64x2x3_t

Available on AArch64 or target_arch=arm64ec only.
1.59.0 · Source§

impl Clone for float64x2x4_t

Available on AArch64 or target_arch=arm64ec only.
1.59.0 · Source§

impl Clone for int8x8_t

Available on (AArch64 or target_arch=arm64ec or target feature v7) and (ARM or AArch64 or target_arch=arm64ec) only.
1.59.0 · Source§

impl Clone for int8x8x2_t

Available on (AArch64 or target_arch=arm64ec or target feature v7) and (ARM or AArch64 or target_arch=arm64ec) only.
1.59.0 · Source§

impl Clone for int8x16_t

Available on (AArch64 or target_arch=arm64ec or target feature v7) and (ARM or AArch64 or target_arch=arm64ec) only.
1.59.0 · Source§

impl Clone for int8x16x2_t

Available on (AArch64 or target_arch=arm64ec or target feature v7) and (ARM or AArch64 or target_arch=arm64ec) only.
1.59.0 · Source§

impl Clone for int16x4_t

Available on (AArch64 or target_arch=arm64ec or target feature v7) and (ARM or AArch64 or target_arch=arm64ec) only.
1.59.0 · Source§

impl Clone for int16x4x2_t

Available on (AArch64 or target_arch=arm64ec or target feature v7) and (ARM or AArch64 or target_arch=arm64ec) only.
1.59.0 · Source§

impl Clone for int16x8_t

Available on (AArch64 or target_arch=arm64ec or target feature v7) and (ARM or AArch64 or target_arch=arm64ec) only.
1.59.0 · Source§

impl Clone for int16x8x2_t

Available on (AArch64 or target_arch=arm64ec or target feature v7) and (ARM or AArch64 or target_arch=arm64ec) only.
1.59.0 · Source§

impl Clone for int32x2_t

Available on (AArch64 or target_arch=arm64ec or target feature v7) and (ARM or AArch64 or target_arch=arm64ec) only.
1.59.0 · Source§

impl Clone for int32x2x2_t

Available on (AArch64 or target_arch=arm64ec or target feature v7) and (ARM or AArch64 or target_arch=arm64ec) only.
1.59.0 · Source§

impl Clone for int32x4_t

Available on (AArch64 or target_arch=arm64ec or target feature v7) and (ARM or AArch64 or target_arch=arm64ec) only.
1.59.0 · Source§

impl Clone for int32x4x2_t

Available on (AArch64 or target_arch=arm64ec or target feature v7) and (ARM or AArch64 or target_arch=arm64ec) only.
1.59.0 · Source§

impl Clone for int64x1_t

Available on (AArch64 or target_arch=arm64ec or target feature v7) and (ARM or AArch64 or target_arch=arm64ec) only.
1.59.0 · Source§

impl Clone for int64x2_t

Available on (AArch64 or target_arch=arm64ec or target feature v7) and (ARM or AArch64 or target_arch=arm64ec) only.
1.59.0 · Source§

impl Clone for poly8x8_t

Available on (AArch64 or target_arch=arm64ec or target feature v7) and (ARM or AArch64 or target_arch=arm64ec) only.
1.59.0 · Source§

impl Clone for poly8x16_t

Available on (AArch64 or target_arch=arm64ec or target feature v7) and (ARM or AArch64 or target_arch=arm64ec) only.
1.59.0 · Source§

impl Clone for poly16x4_t

Available on (AArch64 or target_arch=arm64ec or target feature v7) and (ARM or AArch64 or target_arch=arm64ec) only.
1.59.0 · Source§

impl Clone for poly16x8_t

Available on (AArch64 or target_arch=arm64ec or target feature v7) and (ARM or AArch64 or target_arch=arm64ec) only.
1.59.0 · Source§

impl Clone for poly64x1_t

Available on (AArch64 or target_arch=arm64ec or target feature v7) and (ARM or AArch64 or target_arch=arm64ec) only.
1.59.0 · Source§

impl Clone for poly64x2_t

Available on (AArch64 or target_arch=arm64ec or target feature v7) and (ARM or AArch64 or target_arch=arm64ec) only.
1.59.0 · Source§

impl Clone for uint8x8_t

Available on (AArch64 or target_arch=arm64ec or target feature v7) and (ARM or AArch64 or target_arch=arm64ec) only.
1.59.0 · Source§

impl Clone for uint8x8x2_t

Available on (AArch64 or target_arch=arm64ec or target feature v7) and (ARM or AArch64 or target_arch=arm64ec) only.
1.59.0 · Source§

impl Clone for uint8x16_t

Available on (AArch64 or target_arch=arm64ec or target feature v7) and (ARM or AArch64 or target_arch=arm64ec) only.
1.59.0 · Source§

impl Clone for uint16x4_t

Available on (AArch64 or target_arch=arm64ec or target feature v7) and (ARM or AArch64 or target_arch=arm64ec) only.
1.59.0 · Source§

impl Clone for uint16x8_t

Available on (AArch64 or target_arch=arm64ec or target feature v7) and (ARM or AArch64 or target_arch=arm64ec) only.
1.59.0 · Source§

impl Clone for uint32x2_t

Available on (AArch64 or target_arch=arm64ec or target feature v7) and (ARM or AArch64 or target_arch=arm64ec) only.
1.59.0 · Source§

impl Clone for uint32x4_t

Available on (AArch64 or target_arch=arm64ec or target feature v7) and (ARM or AArch64 or target_arch=arm64ec) only.
1.59.0 · Source§

impl Clone for uint64x1_t

Available on (AArch64 or target_arch=arm64ec or target feature v7) and (ARM or AArch64 or target_arch=arm64ec) only.
1.59.0 · Source§

impl Clone for uint64x2_t

Available on (AArch64 or target_arch=arm64ec or target feature v7) and (ARM or AArch64 or target_arch=arm64ec) only.
1.34.0 · Source§

impl Clone for TryFromSliceError

1.0.0 · Source§

impl Clone for EscapeDefault

1.34.0 · Source§

impl Clone for CharTryFromError

1.9.0 · Source§

impl Clone for DecodeUtf16Error

1.20.0 · Source§

impl Clone for EscapeDebug

1.0.0 · Source§

impl Clone for Error

Source§

impl Clone for FormattingOptions

1.0.0 · Source§

impl Clone for ParseIntError

1.34.0 · Source§

impl Clone for TryFromIntError

1.0.0 (const: unstable) · Source§

impl Clone for RangeFull

Source§

impl Clone for core::ptr::Alignment

1.0.0 · Source§

impl Clone for Utf8Error

1.3.0 · Source§

impl Clone for Duration

1.66.0 · Source§

impl Clone for TryFromFloatSecsError

1.0.0 · Source§

impl<'a> Clone for Arguments<'a>

1.10.0 · Source§

impl<'a> Clone for Location<'a>

Source§

impl<'a> Clone for CharSearcher<'a>

1.0.0 · Source§

impl<'a> Clone for Bytes<'a>

1.0.0 · Source§

impl<'a> Clone for CharIndices<'a>

1.0.0 · Source§

impl<'a> Clone for Chars<'a>

Source§

impl<'a, 'b> Clone for StrSearcher<'a, 'b>

1.0.0 · Source§

impl<A: Clone> Clone for core::option::IntoIter<A>

1.0.0 · Source§

impl<A: Clone, B: Clone> Clone for Chain<A, B>

1.0.0 · Source§

impl<A: Clone, B: Clone> Clone for Zip<A, B>

1.55.0 (const: unstable) · Source§

impl<B: Clone, C: Clone> Clone for ControlFlow<B, C>

Source§

impl<Dyn: PointeeSized> Clone for DynMetadata<Dyn>

1.34.0 · Source§

impl<F: Clone> Clone for FromFn<F>

1.9.0 · Source§

impl<I> Clone for DecodeUtf16<I>
where I: Iterator<Item = u16> + Clone,

1.1.0 · Source§

impl<I: Clone> Clone for Cloned<I>

1.36.0 · Source§

impl<I: Clone> Clone for Copied<I>

1.0.0 · Source§

impl<I: Clone> Clone for Enumerate<I>

1.0.0 · Source§

impl<I: Clone> Clone for Fuse<I>

1.0.0 · Source§

impl<I: Clone> Clone for Skip<I>

1.28.0 · Source§

impl<I: Clone> Clone for StepBy<I>

1.0.0 · Source§

impl<I: Clone> Clone for Take<I>

1.0.0 · Source§

impl<I: Clone, F: Clone> Clone for Map<I, F>

1.0.0 · Source§

impl<I: Clone, P: Clone> Clone for Filter<I, P>

1.0.0 · Source§

impl<I: Clone, P: Clone> Clone for TakeWhile<I, P>

1.0.0 · Source§

impl<I: Clone, U, F: Clone> Clone for FlatMap<I, U, F>
where U: Clone + IntoIterator<IntoIter: Clone>,

1.0.0 (const: unstable) · Source§

impl<Idx: Clone> Clone for Range<Idx>

1.0.0 (const: unstable) · Source§

impl<Idx: Clone> Clone for RangeFrom<Idx>

1.26.0 · Source§

impl<Idx: Clone> Clone for RangeInclusive<Idx>

1.0.0 (const: unstable) · Source§

impl<Idx: Clone> Clone for RangeTo<Idx>

1.26.0 · Source§

impl<Idx: Clone> Clone for RangeToInclusive<Idx>

Source§

impl<P: Clone + ?Sized> Clone for MaybeDangling<P>

1.0.0 (const: unstable) · Source§

impl<T> Clone for Option<T>
where T: Clone,

1.28.0 · Source§

impl<T> Clone for NonZero<T>
where T: ZeroablePrimitive,

1.0.0 · Source§

impl<T> Clone for Iter<'_, T>

1.0.0 · Source§

impl<T, E> Clone for Result<T, E>
where T: Clone, E: Clone,

1.36.0 · Source§

impl<T: Copy> Clone for MaybeUninit<T>

1.0.0 (const: unstable) · Source§

impl<T: PointeeSized> Clone for *const T

1.0.0 (const: unstable) · Source§

impl<T: PointeeSized> Clone for *mut T

1.0.0 (const: unstable) · Source§

impl<T: PointeeSized> Clone for &T

Shared references can be cloned, but mutable references cannot!

1.0.0 · Source§

impl<T: PointeeSized> Clone for PhantomData<T>

1.25.0 · Source§

impl<T: PointeeSized> Clone for NonNull<T>

1.20.0 · Source§

impl<T: Clone + ?Sized> Clone for ManuallyDrop<T>

1.17.0 (const: unstable) · Source§

impl<T: Clone> Clone for Bound<T>

1.0.0 · Source§

impl<T: Clone> Clone for Rev<T>

1.58.0 · Source§

impl<T: Clone, const N: usize> Clone for [T; N]

1.51.0 · Source§

impl<T: Clone, const N: usize> Clone for core::array::IntoIter<T, N>