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 float32x4x2_timpl Clone for vector_bool_shortimpl<T: $crate::clone::Clone> Clone for Rev<T>impl Clone for SipHasherimpl Clone for int8x16_timpl Clone for float32x4x4_timpl Clone for vector_unsigned_intimpl<Dyn: PointeeSized> Clone for DynMetadata<Dyn>impl<I: $crate::clone::Clone> Clone for Skip<I>impl<'a> Clone for EscapeAscii<'a>impl Clone for poly8x16_timpl Clone for int64x1x3_timpl Clone for vector_signed_long_longimpl<I: $crate::clone::Clone> Clone for StepBy<I>impl Clone for uint16x8_timpl Clone for int64x2x2_timpl Clone for vector_bool_long_longimpl<T: $crate::clone::Clone, N: usize> Clone for IntoIter<T, N>impl<I: $crate::clone::Clone, P: $crate::clone::Clone> Clone for TakeWhile<I, P>impl<'a> Clone for Lines<'a>impl Clone for int32x4_timpl Clone for int64x2x4_timpl Clone for vector_doubleimpl Clone for Orderingimpl<T: Clone, N: usize> Clone for [T; N]impl<T> Clone for Empty<T>impl<'a> Clone for SplitWhitespace<'a>impl Clone for float32x4_timpl Clone for uint64x1x3_timpl Clone for HvxVectorPairimpl Clone for Infallibleimpl Clone for EscapeDefaultimpl<F: $crate::clone::Clone> Clone for FromFn<F>impl Clone for uint64x2_timpl Clone for uint64x2x2_timpl Clone for HvxVectorimpl<T: Clone> Clone for OnceCell<T>impl<F: $crate::clone::Clone> Clone for OnceWith<F>impl<'a, T> Clone for RChunksExact<'a, T>impl<'a> Clone for EscapeDebug<'a>impl Clone for float16x4_timpl Clone for uint64x2x4_timpl Clone for HvxVectorPredimpl<'a> Clone for PhantomContravariantLifetime<'a>impl<T: Clone> Clone for RefCell<T>impl<I: Clone, U, F: Clone> Clone for FlatMap<I, U, F>impl<A: $crate::clone::Clone> Clone for RepeatN<A>impl<T> Clone for Iter<'_, T>impl Clone for GetDisjointMutErrorimpl<'a> Clone for EscapeUnicode<'a>impl Clone for int8x8x2_timpl Clone for poly64x1x3_timpl<T, N: usize> Clone for Simd<T, N>impl Clone for CharTryFromErrorimpl Clone for TryFromIntErrorimpl<T: $crate::clone::Clone, F: $crate::clone::Clone> Clone for Successors<T, F>impl Clone for ParseBoolErrorimpl Clone for SearchStepimpl Clone for int8x8x4_timpl Clone for poly64x2x2_timpl Clone for u8impl Clone for DecodeUtf16Errorimpl Clone for Ipv4Addrimpl<'a> Clone for CharIndices<'a>impl<'a, N: usize> Clone for CharArraySearcher<'a, N>impl Clone for int8x16x3_timpl Clone for poly64x2x4_timpl Clone for u64impl Clone for EscapeDefaultimpl Clone for Ipv6MulticastScopeimpl<'a, 'b> Clone for CharSliceSearcher<'a, 'b>impl Clone for uint8x8x2_timpl Clone for __m128impl Clone for i8impl Clone for ToUppercaseimpl<I, F, N: usize> Clone for MapWindows<I, F, N>impl Clone for SocketAddrimpl<'a, P> Clone for SplitTerminator<'a, P>impl<'a, 'b> Clone for StrSearcher<'a, 'b>impl Clone for uint8x8x4_timpl Clone for __m256iimpl<T> Clone for NonZero<T>impl Clone for i64impl Clone for ToLowercaseimpl Clone for SocketAddrV6impl<'a, P> Clone for SplitN<'a, P>impl<'a> Clone for Utf8Chunks<'a>impl Clone for uint8x16x3_timpl Clone for __m256dimpl Clone for f32impl Clone for CharCaseimpl Clone for ParseFloatErrorimpl<'a, P> Clone for MatchIndices<'a, P>impl Clone for TryFromFloatSecsErrorimpl Clone for poly8x8x2_timpl Clone for Localityimpl Clone for __m512impl Clone for boolimpl Clone for FromBytesUntilNulErrorimpl<A: $crate::clone::Clone> Clone for OptionFlatten<A>impl<T, P> Clone for Split<'_, T, P>impl<'a, P> Clone for Matches<'a, P>impl<T: $crate::clone::Clone> Clone for Ready<T>impl Clone for poly8x8x4_timpl Clone for __m128bhimpl<T: PointeeSized> Clone for *const Timpl<T, P> Clone for RSplit<'_, T, P>impl Clone for RawWakerVTableimpl Clone for poly8x16x3_timpl Clone for __m512bhimpl<T> Clone for Chunks<'_, T>impl Clone for int16x4x2_timpl Clone for __m256himpl<T, N: usize> Clone for ArrayWindows<'_, T, N>impl<'a, P: Pattern<Searcher<'a>: Clone>> Clone for SplitInclusive<'a, P>impl Clone for int16x4x4_timpl Clone for bf16impl<T: ?Sized, VARIANT: u32, FIELD: u32> Clone for FieldRepresentingType<T, VARIANT, FIELD>impl Clone for int16x8x3_timpl Clone for FpCategoryimpl Clone for float64x1_timpl Clone for uint16x4x2_timpl Clone for float64x1x2_timpl<T> Clone for PhantomCovariant<T>impl Clone for IntErrorKindimpl Clone for uint16x4x4_timpl Clone for float64x1x4_timpl<T> Clone for PhantomInvariant<T>impl Clone for uint16x8x3_timpl Clone for float64x2x3_timpl Clone for PhantomPinnedimpl<'a, P> Clone for Split<'a, P>impl Clone for poly16x4x2_timpl Clone for v128impl<Y: $crate::clone::Clone, R: $crate::clone::Clone> Clone for CoroutineState<Y, R>impl Clone for poly16x4x4_timpl Clone for vector_unsigned_charimpl<Idx: ~const $crate::clone::Clone> Clone for Range<Idx>impl Clone for poly16x8x3_timpl Clone for vector_signed_shortimpl<Idx: ~const $crate::clone::Clone> Clone for RangeTo<Idx>impl<A> Clone for Iter<'_, A>impl Clone for int32x2x2_timpl Clone for vector_bool_shortimpl<Idx: $crate::clone::Clone> Clone for RangeToInclusive<Idx>impl Clone for int32x2x4_timpl Clone for vector_unsigned_intimpl<'f> Clone for VaList<'f>impl Clone for ParseIntErrorimpl<Ptr: $crate::clone::Clone> Clone for Pin<Ptr>impl Clone for int32x4x3_timpl Clone for vector_floatimpl<T: PointeeSized> Clone for &mut Timpl<A: $crate::clone::Clone, B: $crate::clone::Clone> Clone for Chain<A, B>impl<A: $crate::clone::Clone> Clone for RangeInclusiveIter<A>impl Clone for uint32x2x2_timpl Clone for vector_unsigned_longimpl<T: Clone> Clone for Reverse<T>impl<I: $crate::clone::Clone> Clone for Copied<I>impl<Idx: ~const $crate::clone::Clone> Clone for Range<Idx>impl Clone for Layoutimpl Clone for uint32x2x4_timpl Clone for vector_doubleimpl<I: $crate::clone::Clone> Clone for Enumerate<I>impl<Idx: ~const $crate::clone::Clone> Clone for RangeFrom<Idx>impl Clone for AllocErrorimpl Clone for uint32x4x3_timpl Clone for m256iimpl<I: $crate::clone::Clone, F: $crate::clone::Clone> Clone for FilterMap<I, F>impl<T, E> Clone for Result<T, E>impl Clone for uint8x8_timpl<T: $crate::clone::Clone> Clone for Saturating<T>impl Clone for float16x4x2_timpl Clone for m256dimpl<T: $crate::clone::Clone> Clone for IntoIter<T>impl Clone for int16x4_timpl Clone for float16x4x4_timpl Clone for m128impl Clone for usizeimpl<I: $crate::clone::Clone, F: $crate::clone::Clone> Clone for Inspect<I, F>impl Clone for poly16x4_timpl Clone for float16x8x3_timpl Clone for vector_signed_charimpl Clone for u32impl Clone for Errorimpl Clone for uint32x2_timpl Clone for float32x2x2_timpl Clone for vector_bool_charimpl Clone for isizeimpl<I: $crate::clone::Clone, P: $crate::clone::Clone> Clone for MapWhile<I, P>impl Clone for DebugAsHeximpl Clone for int64x1_timpl Clone for float32x2x4_timpl Clone for vector_unsigned_shortimpl Clone for i32impl<I: $crate::clone::Clone + Iterator> Clone for Peekable<I>impl<'a> Clone for Arguments<'a>impl Clone for poly64x1_timpl Clone for float32x4x3_timpl Clone for vector_signed_intimpl Clone for f16impl<I: $crate::clone::Clone, St: $crate::clone::Clone, F: $crate::clone::Clone> Clone for Scan<I, St, F>impl<H> Clone for BuildHasherDefault<H>impl Clone for uint8x16_timpl Clone for int64x1x2_timpl Clone for vector_bool_intimpl Clone for f128impl<I: $crate::clone::Clone, P: $crate::clone::Clone> Clone for SkipWhile<I, P>impl Clone for int16x8_timpl Clone for int64x1x4_timpl Clone for vector_unsigned_long_longimpl Clone for neverimpl Clone for TypeIdimpl<I: $crate::clone::Clone> Clone for Take<I>impl<P: $crate::clone::Clone + ?Sized> Clone for MaybeDangling<P>impl Clone for poly16x8_timpl Clone for int64x2x3_timpl Clone for vector_floatimpl<T: PointeeSized> Clone for &Timpl Clone for TryFromSliceErrorimpl<A: $crate::clone::Clone, B: $crate::clone::Clone> Clone for Zip<A, B>impl<'a> Clone for LinesAny<'a>impl Clone for Wakerimpl Clone for uint32x4_timpl Clone for uint64x1x2_timpl Clone for HvxVectorimpl Clone for AsciiCharimpl<G: $crate::clone::Clone> Clone for FromCoroutine<G>impl<'a> Clone for SplitAsciiWhitespace<'a>impl Clone for int64x2_timpl Clone for uint64x1x4_timpl Clone for HvxVectorPredimpl<'a> Clone for Source<'a>impl<I: $crate::clone::Clone> Clone for FromIter<I>impl<T: $crate::clone::Clone> Clone for Once<T>impl<T: $crate::clone::Clone> Clone for Wrapping<T>impl<'a> Clone for EncodeUtf16<'a>impl Clone for poly64x2_timpl Clone for uint64x2x3_timpl Clone for HvxVectorPairimpl<'a> Clone for PhantomCovariantLifetime<'a>impl<T: Copy> Clone for Cell<T>impl<A: $crate::clone::Clone> Clone for Repeat<A>impl<'a> Clone for EscapeDefault<'a>impl Clone for float16x8_timpl Clone for poly64x1x2_timpl<'a> Clone for PhantomInvariantLifetime<'a>impl Clone for ParseCharErrorimpl<I, U> Clone for Flatten<I>impl<F: $crate::clone::Clone> Clone for RepeatWith<F>impl<T: Copy> Clone for MaybeUninit<T>impl Clone for Utf8Errorimpl<'a> Clone for Utf8Pattern<'a>impl Clone for int8x8x3_timpl Clone for poly64x1x4_timpl<I> Clone for DecodeUtf16<I>impl Clone for IpAddrimpl<T> Clone for Exclusive<T>impl<'a> Clone for Chars<'a>impl<'a> Clone for CharSearcher<'a>impl Clone for int8x16x2_timpl Clone for poly64x2x3_timpl Clone for EscapeUnicodeimpl<I, G> Clone for IntersperseWith<I, G>impl Clone for Ipv6Addrimpl<'a> Clone for Bytes<'a>impl<'a, 'b, N: usize> Clone for CharArrayRefSearcher<'a, 'b, N>impl Clone for int8x16x4_timpl Clone for __m128iimpl Clone for EscapeDebugimpl Clone for AddrParseErrorimpl<'a, P> Clone for RSplit<'a, P>impl<'a, F> Clone for CharPredicateSearcher<'a, F>impl Clone for uint8x8x3_timpl Clone for __m128dimpl Clone for ToTitlecaseimpl Clone for SocketAddrV4impl<'a, P> Clone for RSplitTerminator<'a, P>impl<'a> Clone for Utf8Chunk<'a>impl Clone for uint8x16x2_timpl Clone for __m256impl Clone for TryFromCharErrorimpl Clone for Alignmentimpl<T> Clone for Option<T>impl<'a, P> Clone for RSplitN<'a, P>impl Clone for Durationimpl Clone for uint8x16x4_timpl Clone for __m512iimpl Clone for FromBytesWithNulErrorimpl<A: $crate::clone::Clone> Clone for IntoIter<A>impl<T> Clone for Iter<'_, T>impl<'a, P> Clone for RMatchIndices<'a, P>impl Clone for poly8x8x3_timpl Clone for __m512dimpl<'a> Clone for Bytes<'a>impl<T, P> Clone for SplitInclusive<'_, T, P>impl<'a, P> Clone for RMatches<'a, P>impl<T: $crate::clone::Clone> Clone for Poll<T>impl Clone for poly8x16x2_timpl Clone for __m256bhimpl<T> Clone for Windows<'_, T>impl Clone for poly8x16x4_timpl Clone for __m128himpl<T> Clone for ChunksExact<'_, T>impl Clone for int16x4x3_timpl Clone for __m512himpl<T> Clone for Discriminant<T>impl<T> Clone for RChunks<'_, T>impl Clone for int16x8x2_timpl Clone for CpuidResultimpl<T: PointeeSized> Clone for NonNull<T>impl<'a, T: 'a, P: Clone> Clone for ChunkBy<'a, T, P>impl Clone for int16x8x4_timpl Clone for float64x2_timpl<T, N: usize> Clone for Mask<T, N>impl Clone for uint16x4x3_timpl Clone for float64x1x3_timpl<T> Clone for PhantomContravariant<T>impl Clone for uint16x8x2_timpl Clone for float64x2x2_timpl Clone for u16impl<T: PointeeSized> Clone for PhantomData<T>impl<T: $crate::clone::Clone + ?Sized> Clone for ManuallyDrop<T>impl Clone for uint16x8x4_timpl Clone for float64x2x4_timpl Clone for u128impl<B: ~const $crate::clone::Clone, C: ~const $crate::clone::Clone> Clone for ControlFlow<B, C>impl Clone for poly16x4x3_timpl Clone for vector_signed_charimpl Clone for i16impl Clone for RangeFullimpl Clone for poly16x8x2_timpl Clone for vector_bool_charimpl Clone for i128impl<Idx: ~const $crate::clone::Clone> Clone for RangeFrom<Idx>impl Clone for poly16x8x4_timpl Clone for vector_unsigned_shortimpl Clone for f64impl<Idx: $crate::clone::Clone> Clone for RangeInclusive<Idx>impl<T> Clone for Pending<T>impl Clone for int32x2x3_timpl Clone for vector_signed_intimpl Clone for charimpl<T: ~const $crate::clone::Clone> Clone for Bound<T>impl<'a> Clone for Location<'a>impl Clone for int32x4x2_timpl Clone for vector_bool_intimpl<T: PointeeSized> Clone for *mut Timpl<I: $crate::clone::Clone + Iterator, N: usize> Clone for ArrayChunks<I, N>impl<A: $crate::clone::Clone> Clone for RangeIter<A>impl Clone for int32x4x4_timpl Clone for vector_signed_longimpl<I: $crate::clone::Clone> Clone for Cloned<I>impl<A: $crate::clone::Clone> Clone for RangeFromIter<A>impl Clone for LocalWakerimpl Clone for uint32x2x3_timpl Clone for vector_bool_longimpl<I: $crate::clone::Clone> Clone for Cycle<I>impl<Idx: $crate::clone::Clone> Clone for RangeInclusive<Idx>impl Clone for LayoutErrorimpl Clone for uint32x4x2_timpl Clone for f16x2impl<I: $crate::clone::Clone, P: $crate::clone::Clone> Clone for Filter<I, P>impl<Idx: $crate::clone::Clone> Clone for RangeToInclusive<Idx>impl Clone for int8x8_timpl Clone for uint32x4x4_timpl Clone for m256impl Clone for poly8x8_timpl Clone for float16x4x3_timpl Clone for m128iimpl<I: $crate::clone::Clone> Clone for Fuse<I>impl Clone for Orderingimpl Clone for uint16x4_timpl Clone for float16x8x2_timpl Clone for m128dimpl<I: $crate::clone::Clone + Iterator> Clone for Intersperse<I>impl Clone for Alignmentimpl Clone for Assumeimpl Clone for int32x2_timpl Clone for float16x8x4_timpl Clone for vector_unsigned_charimpl<I: $crate::clone::Clone, F: $crate::clone::Clone> Clone for Map<I, F>impl Clone for Signimpl Clone for float32x2_timpl Clone for float32x2x3_timpl Clone for vector_signed_shortimpl Clone for FormattingOptionsimpl Clone for uint64x1_t