Trait Clone
trait Clone: Sized
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.
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:
);
If we derive:
);
the auto-derived implementations will have unnecessary T: Copy and T: Clone bounds:
# );
// Automatically derived
// Automatically derived
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
Clonethemselves. Note that variables captured by shared reference always implementClone(even if the referent doesn't), while variables captured by mutable reference never implementClone.
Required Methods
fn clone(self: &Self) -> SelfReturns 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
ArcorRc, this increments the reference count but still points to the same underlying data
Examples
# let hello = "Hello"; // &str implements Clone assert_eq!;Example with a reference-counted type:
use ; let data = new; let data_clone = data.clone; // Creates another Arc pointing to the same Mutex // Changes are visible through the clone because they share the same underlying data assert_eq!;
Provided Methods
fn clone_from(self: &mut Self, source: &Self) where Self:Performs copy-assignment from
source.a.clone_from(&b)is equivalent toa = b.clone()in functionality, but can be overridden to reuse the resources ofato avoid unnecessary allocations.
Implementors
impl Clone for i64impl Clone for int16x4x3_timpl Clone for CpuidResultimpl<P: $crate::clone::Clone + ?Sized> Clone for MaybeDangling<P>impl Clone for poly64x2_timpl Clone for poly64x1x2_timpl<'a> Clone for PhantomContravariantLifetime<'a>impl Clone for Ipv4Addrimpl<'a, 'b> Clone for CharSliceSearcher<'a, 'b>impl<Idx: ~const $crate::clone::Clone> Clone for RangeFrom<Idx>impl Clone for uint8x8_timpl Clone for float16x4x4_timpl Clone for vector_signed_charimpl Clone for FromBytesWithNulErrorimpl<T, P> Clone for SplitInclusive<'_, T, P>impl<I: $crate::clone::Clone, F: $crate::clone::Clone> Clone for Map<I, F>impl Clone for uint16x8x3_timpl Clone for v128impl<'a> Clone for CharIndices<'a>impl Clone for uint8x8x2_timpl Clone for __m256iimpl Clone for charimpl<A: $crate::clone::Clone> Clone for IntoIter<A>impl<T: $crate::clone::Clone> Clone for Poll<T>impl<T> Clone for NonZero<T>impl Clone for ParseIntErrorimpl Clone for Signimpl Clone for uint64x1_timpl Clone for float32x4x4_timpl Clone for vector_signed_long_longimpl<I: $crate::clone::Clone> Clone for Take<I>impl<'a> Clone for LinesAny<'a>impl<T: PointeeSized> Clone for PhantomData<T>impl Clone for int32x2x3_timpl Clone for vector_bool_intimpl<T: Clone> Clone for OnceCell<T>impl<A: $crate::clone::Clone, B: $crate::clone::Clone> Clone for Chain<A, B>impl Clone for u64impl<'a, P> Clone for RMatchIndices<'a, P>impl Clone for poly8x16x2_timpl Clone for __m128himpl Clone for uint32x4_timpl Clone for uint64x1x4_timpl<A: $crate::clone::Clone> Clone for RepeatN<A>impl Clone for SearchStepimpl<T: $crate::clone::Clone> Clone for Saturating<T>impl Clone for TryFromIntErrorimpl<Idx: $crate::clone::Clone> Clone for RangeToInclusive<Idx>impl<A: $crate::clone::Clone> Clone for RangeInclusiveIter<A>impl Clone for Layoutimpl Clone for uint32x4x3_timpl Clone for m256dimpl Clone for EscapeDebugimpl<T, N: usize> Clone for Mask<T, N>impl<I: $crate::clone::Clone> Clone for Fuse<I>impl Clone for uint16x4x2_timpl Clone for float64x1x4_timpl<T: $crate::clone::Clone + ?Sized> Clone for ManuallyDrop<T>impl Clone for GetDisjointMutErrorimpl Clone for int8x8x4_timpl Clone for poly64x2x4_timpl Clone for i128impl Clone for SocketAddrV4impl Clone for Durationimpl Clone for Orderingimpl Clone for int32x2_timpl Clone for float32x2x3_timpl Clone for vector_bool_shortimpl<I: $crate::clone::Clone, St: $crate::clone::Clone, F: $crate::clone::Clone> Clone for Scan<I, St, F>impl Clone for poly16x8x2_timpl Clone for vector_unsigned_shortimpl<T: Clone, N: usize> Clone for [T; N]impl<'a, P> Clone for RSplitTerminator<'a, P>impl Clone for uint8x16x4_timpl Clone for __m512dimpl<T: Clone> Clone for Reverse<T>impl<H> Clone for BuildHasherDefault<H>impl Clone for int16x8_timpl Clone for int64x2x3_timpl Clone for neverimpl<F: $crate::clone::Clone> Clone for FromFn<F>impl<'a> Clone for EscapeDebug<'a>impl<Idx: ~const $crate::clone::Clone> Clone for Range<Idx>impl Clone for uint32x2x2_timpl Clone for vector_doubleimpl<I> Clone for DecodeUtf16<I>impl<I: $crate::clone::Clone, P: $crate::clone::Clone> Clone for Filter<I, P>impl Clone for int16x4x4_timpl Clone for float64x1_timpl<'a, T: $crate::clone::Clone + 'a, N: usize> Clone for ArrayWindows<'a, T, N>impl Clone for float16x4_timpl Clone for poly64x1x3_timpl Clone for u128impl<'a> Clone for PhantomInvariantLifetime<'a>impl Clone for Ipv6Addrimpl<'a, F> Clone for CharPredicateSearcher<'a, F>impl<Idx: $crate::clone::Clone> Clone for RangeToInclusive<Idx>impl Clone for poly8x8_timpl Clone for float16x8x2_timpl Clone for vector_unsigned_charimpl Clone for FromBytesUntilNulErrorimpl<T, P> Clone for RSplit<'_, T, P>impl<I: $crate::clone::Clone, P: $crate::clone::Clone> Clone for MapWhile<I, P>impl Clone for uint16x8x4_timpl Clone for vector_signed_charimpl<'a> Clone for Bytes<'a>impl Clone for uint8x8x3_timpl Clone for __m256impl<A: $crate::clone::Clone> Clone for OptionFlatten<A>impl Clone for RawWakerVTableimpl Clone for DebugAsHeximpl Clone for poly64x1_timpl Clone for int64x1x2_timpl Clone for vector_unsigned_long_longimpl Clone for f16impl<I: $crate::clone::Clone, P: $crate::clone::Clone> Clone for TakeWhile<I, P>impl<'a> Clone for SplitWhitespace<'a>impl Clone for PhantomPinnedimpl Clone for int32x2x4_timpl Clone for vector_floatimpl<T: Copy> Clone for Cell<T>impl<T> Clone for Exclusive<T>impl<I: $crate::clone::Clone> Clone for Cloned<I>impl<'a, P> Clone for Matches<'a, P>impl Clone for poly8x16x3_timpl Clone for __m256himpl Clone for IntErrorKindimpl Clone for float32x4_timpl Clone for uint64x2x2_timpl Clone for Infallibleimpl<F: $crate::clone::Clone> Clone for RepeatWith<F>impl<'a> Clone for CharSearcher<'a>impl<T: ~const $crate::clone::Clone> Clone for Bound<T>impl<A: $crate::clone::Clone> Clone for RangeFromIter<A>impl Clone for LayoutErrorimpl Clone for uint32x4x4_timpl Clone for m128iimpl Clone for ToLowercaseimpl<I: $crate::clone::Clone, F: $crate::clone::Clone> Clone for Inspect<I, F>impl<T: PointeeSized> Clone for *const Timpl Clone for uint16x4x3_timpl Clone for float64x2x2_timpl Clone for Utf8Errorimpl Clone for int8x16x2_timpl Clone for __m128iimpl Clone for SocketAddrV6impl Clone for TryFromFloatSecsErrorimpl Clone for uint32x2_timpl Clone for float32x2x4_timpl Clone for vector_signed_intimpl<T> Clone for RChunks<'_, T>impl<T: $crate::clone::Clone> Clone for Wrapping<T>impl Clone for isizeimpl<I: $crate::clone::Clone> Clone for Skip<I>impl<T> Clone for PhantomCovariant<T>impl Clone for poly16x8x3_timpl Clone for vector_bool_shortimpl Clone for AsciiCharimpl<I, F, N: usize> Clone for MapWindows<I, F, N>impl<'a, P> Clone for SplitN<'a, P>impl Clone for poly8x8x2_timpl Clone for __m128bhimpl<'a> Clone for EscapeAscii<'a>impl Clone for uint16x8_timpl Clone for int64x2x4_timpl<'a, P> Clone for Split<'a, P>impl<T: $crate::clone::Clone> Clone for Once<T>impl<'a> Clone for EscapeDefault<'a>impl<Idx: ~const $crate::clone::Clone> Clone for RangeFrom<Idx>impl<'a> Clone for Location<'a>impl Clone for uint32x2x3_timpl Clone for f16x2impl Clone for DecodeUtf16Errorimpl<I: $crate::clone::Clone, F: $crate::clone::Clone> Clone for FilterMap<I, F>impl Clone for FpCategoryimpl Clone for f32impl Clone for int16x8x2_timpl Clone for float64x2_timpl Clone for float16x8_timpl Clone for poly64x1x4_timpl Clone for Ipv6MulticastScopeimpl<'a, 'b> Clone for StrSearcher<'a, 'b>impl<T, E> Clone for Result<T, E>impl Clone for int16x4_timpl Clone for float16x8x3_timpl Clone for vector_bool_charimpl<'a> Clone for Bytes<'a>impl<T> Clone for Windows<'_, T>impl Clone for usizeimpl Clone for poly16x4x2_timpl Clone for vector_unsigned_charimpl Clone for TypeIdimpl Clone for uint8x8x4_timpl Clone for __m256dimpl<T: PointeeSized> Clone for *mut Timpl Clone for FormattingOptionsimpl Clone for int8x16_timpl Clone for int64x1x3_timpl Clone for vector_bool_long_longimpl<A: $crate::clone::Clone, B: $crate::clone::Clone> Clone for Zip<A, B>impl<'a> Clone for SplitAsciiWhitespace<'a>impl<B: ~const $crate::clone::Clone, C: ~const $crate::clone::Clone> Clone for ControlFlow<B, C>impl<T> Clone for Pending<T>impl Clone for int32x4x2_timpl Clone for vector_signed_longimpl<T: Clone> Clone for RefCell<T>impl<I: $crate::clone::Clone> Clone for Copied<I>impl Clone for i8impl<'a, P> Clone for RMatches<'a, P>impl Clone for poly8x16x4_timpl Clone for __m512himpl Clone for int64x2_timpl Clone for uint64x2x3_timpl<'a> Clone for Source<'a>impl<T: $crate::clone::Clone, F: $crate::clone::Clone> Clone for Successors<T, F>impl<'a, N: usize> Clone for CharArraySearcher<'a, N>impl<Idx: ~const $crate::clone::Clone> Clone for Range<Idx>impl Clone for AllocErrorimpl Clone for float16x4x2_timpl Clone for m128impl Clone for ToUppercaseimpl<T> Clone for Iter<'_, T>impl<T, N: usize> Clone for Simd<T, N>impl<I: $crate::clone::Clone + Iterator> Clone for Intersperse<I>impl Clone for uint16x4x4_timpl Clone for float64x2x3_timpl Clone for Wakerimpl<I: Clone, U, F: Clone> Clone for FlatMap<I, U, F>impl Clone for ParseBoolErrorimpl Clone for int8x16x3_timpl Clone for __m128impl Clone for f64impl<T> Clone for Option<T>impl Clone for Alignmentimpl Clone for float32x2_timpl Clone for float32x4x2_timpl Clone for vector_unsigned_intimpl<I: $crate::clone::Clone, P: $crate::clone::Clone> Clone for SkipWhile<I, P>impl Clone for Localityimpl<T> Clone for PhantomContravariant<T>impl Clone for poly16x8x4_timpl Clone for vector_signed_intimpl Clone for EscapeDefaultimpl<T> Clone for Iter<'_, T>impl<'f> Clone for VaList<'f>impl Clone for u8impl<'a, P> Clone for RSplitN<'a, P>impl Clone for poly8x8x3_timpl Clone for __m256bhimpl Clone for poly16x8_timpl Clone for uint64x1x2_timpl<T: PointeeSized> Clone for &Timpl<F: $crate::clone::Clone> Clone for OnceWith<F>impl<'a> Clone for EscapeUnicode<'a>impl<Idx: ~const $crate::clone::Clone> Clone for RangeTo<Idx>impl<Ptr: $crate::clone::Clone> Clone for Pin<Ptr>impl Clone for uint32x2x4_timpl Clone for m256iimpl Clone for EscapeUnicodeimpl<'a, P: Pattern<Searcher<'a>: Clone>> Clone for SplitInclusive<'a, P>impl Clone for int16x8x3_timpl Clone for float64x1x2_timpl<'a, T> Clone for RChunksExact<'a, T>impl Clone for int8x8x2_timpl Clone for poly64x2x2_timpl Clone for i16impl Clone for AddrParseErrorimpl<'a> Clone for Utf8Chunk<'a>impl Clone for uint16x4_timpl Clone for float16x8x4_timpl Clone for vector_signed_shortimpl<T> Clone for Chunks<'_, T>impl<I: $crate::clone::Clone + Iterator> Clone for Peekable<I>impl Clone for poly16x4x3_timpl Clone for vector_bool_charimpl<T: $crate::clone::Clone, N: usize> Clone for IntoIter<T, N>impl<I, G> Clone for IntersperseWith<I, G>impl<'a, P> Clone for RSplit<'a, P>impl Clone for uint8x16x2_timpl Clone for __m512iimpl<T: PointeeSized> Clone for &mut Timpl<T: Copy> Clone for MaybeUninit<T>impl<'a> Clone for Arguments<'a>impl Clone for uint8x16_timpl Clone for int64x1x4_timpl Clone for vector_floatimpl Clone for f128impl<T> Clone for Empty<T>impl<Y: $crate::clone::Clone, R: $crate::clone::Clone> Clone for CoroutineState<Y, R>impl<A> Clone for Iter<'_, A>impl Clone for int32x4x3_timpl Clone for vector_unsigned_longimpl<T: PointeeSized> Clone for NonNull<T>impl Clone for ParseCharErrorimpl<I: $crate::clone::Clone> Clone for Cycle<I>impl Clone for int16x4x2_timpl Clone for bf16impl Clone for uint64x2_timpl Clone for uint64x2x4_timpl Clone for u16impl<'a> Clone for PhantomCovariantLifetime<'a>impl Clone for IpAddrimpl<'a, 'b, N: usize> Clone for CharArrayRefSearcher<'a, 'b, N>impl<Idx: $crate::clone::Clone> Clone for RangeInclusive<Idx>impl Clone for int8x8_timpl Clone for float16x4x3_timpl Clone for m128dimpl Clone for TryFromCharErrorimpl<T, P> Clone for Split<'_, T, P>impl Clone for uint16x8x2_timpl Clone for float64x2x4_timpl<I, U> Clone for Flatten<I>impl<'a> Clone for Chars<'a>impl Clone for int8x16x4_timpl Clone for __m128dimpl<T: $crate::clone::Clone> Clone for Ready<T>impl Clone for Errorimpl Clone for int64x1_timpl Clone for float32x4x3_timpl Clone for vector_bool_intimpl<'a, T: 'a, P: Clone> Clone for ChunkBy<'a, T, P>impl Clone for i32impl<I: $crate::clone::Clone> Clone for StepBy<I>impl<'a> Clone for Lines<'a>impl<T> Clone for PhantomInvariant<T>impl Clone for int32x2x2_timpl Clone for vector_unsigned_intimpl<I: $crate::clone::Clone> Clone for FromIter<I>impl<I: $crate::clone::Clone + Iterator, N: usize> Clone for ArrayChunks<I, N>impl<'a, P> Clone for MatchIndices<'a, P>impl Clone for poly8x8x4_timpl Clone for __m512bhimpl Clone for int32x4_timpl Clone for uint64x1x3_timpl Clone for Orderingimpl<A: $crate::clone::Clone> Clone for Repeat<A>impl<'a> Clone for Utf8Pattern<'a>impl<Idx: $crate::clone::Clone> Clone for RangeInclusive<Idx>impl<A: $crate::clone::Clone> Clone for RangeIter<A>impl Clone for LocalWakerimpl Clone for uint32x4x2_timpl Clone for m256impl Clone for EscapeDefaultimpl Clone for boolimpl Clone for int16x8x4_timpl Clone for float64x1x3_timpl Clone for int8x8x3_timpl Clone for poly64x2x3_timpl Clone for SocketAddrimpl<'a> Clone for Utf8Chunks<'a>impl<T: $crate::clone::Clone> Clone for IntoIter<T>impl Clone for poly16x4_timpl Clone for float32x2x2_timpl Clone for vector_unsigned_shortimpl<T> Clone for ChunksExact<'_, T>impl Clone for u32impl<T: $crate::clone::Clone> Clone for Rev<T>impl Clone for poly16x4x4_timpl Clone for vector_signed_shortimpl Clone for TryFromSliceErrorimpl<T> Clone for Discriminant<T>impl Clone for Assumeimpl<'a, P> Clone for SplitTerminator<'a, P>impl Clone for uint8x16x3_timpl Clone for __m512impl Clone for SipHasherimpl Clone for poly8x16_timpl Clone for int64x2x2_timpl Clone for vector_doubleimpl Clone for Alignmentimpl<Dyn: PointeeSized> Clone for DynMetadata<Dyn>impl<G: $crate::clone::Clone> Clone for FromCoroutine<G>impl<'a> Clone for EncodeUtf16<'a>impl Clone for RangeFullimpl Clone for int32x4x4_timpl Clone for vector_bool_longimpl Clone for CharTryFromErrorimpl<I: $crate::clone::Clone> Clone for Enumerate<I>