pub trait Clone: Sized {
// Required method
fn clone(&self) -> Self;
// Provided method
fn clone_from(&mut self, source: &Self) { ... }
}
Expand description
A common trait for the ability to explicitly duplicate an object.
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.
§Derivable
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` implements Clone for Reading<T> when T is Clone.
#[derive(Clone)]
struct Reading<T> {
frequency: T,
}
Run§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
}
}
RunIf we derive
:
#[derive(Copy, Clone)]
struct Generate<T>(fn() -> T);
Runthe 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))
}
}
RunThe 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.
Run§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 implementClone
(even if the referent doesn’t), while variables captured by mutable reference never implementClone
.
Required Methods§
Provided Methods§
sourcefn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &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.
Object Safety§
Implementors§
impl Clone for AsciiChar
impl Clone for std::cmp::Ordering
impl Clone for TryReserveErrorKind
impl Clone for Infallible
impl Clone for VarError
impl Clone for std::fmt::Alignment
impl Clone for ErrorKind
impl Clone for SeekFrom
impl Clone for IpAddr
impl Clone for Ipv6MulticastScope
impl Clone for Shutdown
impl Clone for std::net::SocketAddr
impl Clone for FpCategory
impl Clone for IntErrorKind
impl Clone for BacktraceStyle
impl Clone for SearchStep
impl Clone for std::sync::atomic::Ordering
impl Clone for RecvTimeoutError
impl Clone for TryRecvError
impl Clone for DwarfFileType
impl Clone for Format
impl Clone for SectionId
impl Clone for Vendor
impl Clone for RunTimeEndian
impl Clone for AbbreviationsCacheStrategy
impl Clone for Pointer
impl Clone for gimli::read::Error
impl Clone for ColumnType
impl Clone for Value
impl Clone for ValueType
impl Clone for Prefilter
impl Clone for bool
impl Clone for char
impl Clone for f32
impl Clone for f64
impl Clone for i8
impl Clone for i16
impl Clone for i32
impl Clone for i64
impl Clone for i128
impl Clone for isize
impl Clone for !
impl Clone for u8
impl Clone for u16
impl Clone for u32
impl Clone for u64
impl Clone for u128
impl Clone for usize
impl Clone for CpuidResult
impl Clone for __m128
impl Clone for __m128bh
impl Clone for __m128d
impl Clone for __m128i
impl Clone for __m256
impl Clone for __m256bh
impl Clone for __m256d
impl Clone for __m256i
impl Clone for __m512
impl Clone for __m512bh
impl Clone for __m512d
impl Clone for __m512i
impl Clone for TimSortRun
impl Clone for AllocError
impl Clone for Global
impl Clone for Layout
impl Clone for LayoutError
impl Clone for System
impl Clone for TypeId
impl Clone for TryFromSliceError
impl Clone for std::ascii::EscapeDefault
impl Clone for Box<str>
impl Clone for Box<CStr>
impl Clone for Box<OsStr>
impl Clone for Box<Path>
impl Clone for CharTryFromError
impl Clone for DecodeUtf16Error
impl Clone for std::char::EscapeDebug
impl Clone for std::char::EscapeDefault
impl Clone for std::char::EscapeUnicode
impl Clone for ParseCharError
impl Clone for ToLowercase
impl Clone for ToUppercase
impl Clone for TryFromCharError
impl Clone for UnorderedKeyError
impl Clone for DefaultHasher
impl Clone for RandomState
impl Clone for TryReserveError
impl Clone for FromBytesUntilNulError
impl Clone for FromBytesWithNulError
impl Clone for FromVecWithNulError
impl Clone for IntoStringError
impl Clone for NulError
impl Clone for CString
impl Clone for OsString
impl Clone for std::fmt::Error
impl Clone for FileTimes
impl Clone for FileType
impl Clone for Metadata
impl Clone for OpenOptions
impl Clone for Permissions
impl Clone for SipHasher
impl Clone for std::io::Empty
impl Clone for Sink
impl Clone for PhantomPinned
impl Clone for Assume
impl Clone for AddrParseError
impl Clone for Ipv4Addr
impl Clone for Ipv6Addr
impl Clone for SocketAddrV4
impl Clone for SocketAddrV6
impl Clone for ParseFloatError
impl Clone for ParseIntError
impl Clone for TryFromIntError
impl Clone for RangeFull
impl Clone for stat
impl Clone for std::os::unix::net::SocketAddr
impl Clone for SocketCred
impl Clone for UCred
impl Clone for InvalidHandleError
impl Clone for NullHandleError
impl Clone for PathBuf
impl Clone for StripPrefixError
impl Clone for ExitCode
impl Clone for ExitStatus
impl Clone for ExitStatusError
impl Clone for Output
impl Clone for std::ptr::Alignment
impl Clone for ParseBoolError
impl Clone for Utf8Error
impl Clone for FromUtf8Error
impl Clone for String
impl Clone for RecvError
impl Clone for WaitTimeoutResult
impl Clone for LocalWaker
impl Clone for RawWakerVTable
impl Clone for Waker
impl Clone for AccessError
impl Clone for Thread
impl Clone for ThreadId
impl Clone for Duration
impl Clone for Instant
impl Clone for SystemTime
impl Clone for SystemTimeError
impl Clone for TryFromFloatSecsError
impl Clone for AArch64
impl Clone for Arm
impl Clone for LoongArch
impl Clone for RiscV
impl Clone for X86
impl Clone for X86_64
impl Clone for DebugTypeSignature
impl Clone for DwoId
impl Clone for Encoding
impl Clone for LineEncoding
impl Clone for Register
impl Clone for DwAccess
impl Clone for DwAddr
impl Clone for DwAt
impl Clone for DwAte
impl Clone for DwCc
impl Clone for DwCfa
impl Clone for DwChildren
impl Clone for DwDefaulted
impl Clone for DwDs
impl Clone for DwDsc
impl Clone for DwEhPe
impl Clone for DwEnd
impl Clone for DwForm
impl Clone for DwId
impl Clone for DwIdx
impl Clone for DwInl
impl Clone for DwLang
impl Clone for DwLle
impl Clone for DwLnct
impl Clone for DwLne
impl Clone for DwLns
impl Clone for DwMacro
impl Clone for DwOp
impl Clone for DwOrd
impl Clone for DwRle
impl Clone for DwSect
impl Clone for DwSectV2
impl Clone for DwTag
impl Clone for DwUt
impl Clone for DwVirtuality
impl Clone for DwVis
impl Clone for BigEndian
impl Clone for LittleEndian
impl Clone for Abbreviation
impl Clone for Abbreviations
impl Clone for AttributeSpecification
impl Clone for ArangeEntry
impl Clone for Augmentation
impl Clone for BaseAddresses
impl Clone for SectionBaseAddresses
impl Clone for UnitIndexSection
impl Clone for FileEntryFormat
impl Clone for LineRow
impl Clone for ReaderOffsetId
impl Clone for gimli::read::rnglists::Range
impl Clone for StoreOnHeap
impl Clone for FinderBuilder
impl Clone for Adler32
impl<'a> Clone for Component<'a>
impl<'a> Clone for Prefix<'a>
impl<'a> Clone for Source<'a>
impl<'a> Clone for core::ffi::c_str::Bytes<'a>
impl<'a> Clone for Arguments<'a>
impl<'a> Clone for IoSlice<'a>
impl<'a> Clone for EncodeWide<'a>
impl<'a> Clone for std::panic::Location<'a>
impl<'a> Clone for Ancestors<'a>
impl<'a> Clone for Components<'a>
impl<'a> Clone for std::path::Iter<'a>
impl<'a> Clone for PrefixComponent<'a>
impl<'a> Clone for EscapeAscii<'a>
impl<'a> Clone for CharSearcher<'a>
impl<'a> Clone for std::str::Bytes<'a>
impl<'a> Clone for CharIndices<'a>
impl<'a> Clone for Chars<'a>
impl<'a> Clone for EncodeUtf16<'a>
impl<'a> Clone for std::str::EscapeDebug<'a>
impl<'a> Clone for std::str::EscapeDefault<'a>
impl<'a> Clone for std::str::EscapeUnicode<'a>
impl<'a> Clone for Lines<'a>
impl<'a> Clone for LinesAny<'a>
impl<'a> Clone for SplitAsciiWhitespace<'a>
impl<'a> Clone for SplitWhitespace<'a>
impl<'a> Clone for Utf8Chunk<'a>
impl<'a> Clone for Utf8Chunks<'a>
impl<'a, 'b> Clone for CharSliceSearcher<'a, 'b>
impl<'a, 'b> Clone for StrSearcher<'a, 'b>
impl<'a, 'b, const N: usize> Clone for CharArrayRefSearcher<'a, 'b, N>
impl<'a, F> Clone for CharPredicateSearcher<'a, F>
impl<'a, P> Clone for MatchIndices<'a, P>
impl<'a, P> Clone for Matches<'a, P>
impl<'a, P> Clone for RMatchIndices<'a, P>
impl<'a, P> Clone for RMatches<'a, P>
impl<'a, P> Clone for std::str::RSplit<'a, P>
impl<'a, P> Clone for RSplitN<'a, P>
impl<'a, P> Clone for RSplitTerminator<'a, P>
impl<'a, P> Clone for std::str::Split<'a, P>
impl<'a, P> Clone for std::str::SplitInclusive<'a, P>
impl<'a, P> Clone for SplitN<'a, P>
impl<'a, P> Clone for SplitTerminator<'a, P>
impl<'a, R> Clone for CallFrameInstructionIter<'a, R>
impl<'a, R> Clone for EhHdrTable<'a, R>
impl<'a, T> Clone for RChunksExact<'a, T>
impl<'a, T, const N: usize> Clone for ArrayWindows<'a, T, N>where
T: Clone + 'a,
impl<'a, const N: usize> Clone for CharArraySearcher<'a, N>
impl<'abbrev, 'entry, 'unit, R> Clone for AttrsIter<'abbrev, 'entry, 'unit, R>
impl<'abbrev, 'unit, R> Clone for EntriesCursor<'abbrev, 'unit, R>
impl<'abbrev, 'unit, R> Clone for EntriesRaw<'abbrev, 'unit, R>
impl<'abbrev, 'unit, R> Clone for EntriesTree<'abbrev, 'unit, R>
impl<'abbrev, 'unit, R, Offset> Clone for DebuggingInformationEntry<'abbrev, 'unit, R, Offset>
impl<'bases, Section, R> Clone for CieOrFde<'bases, Section, R>
impl<'bases, Section, R> Clone for CfiEntriesIter<'bases, Section, R>
impl<'bases, Section, R> Clone for PartialFrameDescriptionEntry<'bases, Section, R>where
Section: Clone + UnwindSection<R>,
R: Clone + Reader,
<R as Reader>::Offset: Clone,
<Section as UnwindSection<R>>::Offset: Clone,
impl<'f> Clone for VaListImpl<'f>
impl<'fd> Clone for BorrowedFd<'fd>
impl<'handle> Clone for BorrowedHandle<'handle>
impl<'index, R> Clone for UnitIndexSectionIterator<'index, R>
impl<'input, Endian> Clone for EndianSlice<'input, Endian>
impl<'iter, R> Clone for RegisterRuleIter<'iter, R>
impl<'n> Clone for Finder<'n>
impl<'n> Clone for FinderRev<'n>
impl<'socket> Clone for BorrowedSocket<'socket>
impl<A> Clone for Repeat<A>where
A: Clone,
impl<A> Clone for RepeatN<A>where
A: Clone,
impl<A> Clone for std::option::IntoIter<A>where
A: Clone,
impl<A> Clone for std::option::Iter<'_, A>
impl<A, B> Clone for Chain<A, B>
impl<A, B> Clone for Zip<A, B>
impl<B> Clone for Cow<'_, B>
impl<B, C> Clone for ControlFlow<B, C>
impl<Dyn> Clone for DynMetadata<Dyn>where
Dyn: ?Sized,
impl<F> Clone for FromFn<F>where
F: Clone,
impl<F> Clone for OnceWith<F>where
F: Clone,
impl<F> Clone for RepeatWith<F>where
F: Clone,
impl<H> Clone for BuildHasherDefault<H>
impl<I> Clone for FromIter<I>where
I: Clone,
impl<I> Clone for DecodeUtf16<I>
impl<I> Clone for Cloned<I>where
I: Clone,
impl<I> Clone for Copied<I>where
I: Clone,
impl<I> Clone for Cycle<I>where
I: Clone,
impl<I> Clone for Enumerate<I>where
I: Clone,
impl<I> Clone for Fuse<I>where
I: Clone,
impl<I> Clone for Intersperse<I>
impl<I> Clone for Peekable<I>
impl<I> Clone for Skip<I>where
I: Clone,
impl<I> Clone for StepBy<I>where
I: Clone,
impl<I> Clone for Take<I>where
I: Clone,
impl<I, F> Clone for FilterMap<I, F>
impl<I, F> Clone for Inspect<I, F>
impl<I, F> Clone for Map<I, F>
impl<I, F, const N: usize> Clone for MapWindows<I, F, N>
impl<I, G> Clone for IntersperseWith<I, G>
impl<I, P> Clone for Filter<I, P>
impl<I, P> Clone for MapWhile<I, P>
impl<I, P> Clone for SkipWhile<I, P>
impl<I, P> Clone for TakeWhile<I, P>
impl<I, St, F> Clone for Scan<I, St, F>
impl<I, U> Clone for Flatten<I>
impl<I, U, F> Clone for FlatMap<I, U, F>
impl<I, const N: usize> Clone for std::iter::ArrayChunks<I, N>
impl<Idx> Clone for std::ops::Range<Idx>where
Idx: Clone,
impl<Idx> Clone for RangeFrom<Idx>where
Idx: Clone,
impl<Idx> Clone for RangeInclusive<Idx>where
Idx: Clone,
impl<Idx> Clone for RangeTo<Idx>where
Idx: Clone,
impl<Idx> Clone for RangeToInclusive<Idx>where
Idx: Clone,
impl<K> Clone for std::collections::hash_set::Iter<'_, K>
impl<K, V> Clone for std::collections::btree_map::Cursor<'_, K, V>
impl<K, V> Clone for std::collections::btree_map::Iter<'_, K, V>
impl<K, V> Clone for std::collections::btree_map::Keys<'_, K, V>
impl<K, V> Clone for std::collections::btree_map::Range<'_, K, V>
impl<K, V> Clone for std::collections::btree_map::Values<'_, K, V>
impl<K, V> Clone for std::collections::hash_map::Iter<'_, K, V>
impl<K, V> Clone for std::collections::hash_map::Keys<'_, K, V>
impl<K, V> Clone for std::collections::hash_map::Values<'_, K, V>
impl<K, V, A> Clone for BTreeMap<K, V, A>
impl<K, V, S> Clone for HashMap<K, V, S>
impl<Offset> Clone for UnitType<Offset>where
Offset: Clone + ReaderOffset,
impl<Ptr> Clone for Pin<Ptr>where
Ptr: Clone,
impl<R> Clone for CallFrameInstruction<R>
impl<R> Clone for CfaRule<R>
impl<R> Clone for RegisterRule<R>
impl<R> Clone for RawLocListEntry<R>
impl<R> Clone for DebugAbbrev<R>where
R: Clone,
impl<R> Clone for DebugAddr<R>where
R: Clone,
impl<R> Clone for ArangeEntryIter<R>
impl<R> Clone for ArangeHeaderIter<R>
impl<R> Clone for DebugAranges<R>where
R: Clone,
impl<R> Clone for DebugFrame<R>
impl<R> Clone for EhFrame<R>
impl<R> Clone for EhFrameHdr<R>
impl<R> Clone for ParsedEhFrameHdr<R>
impl<R> Clone for DebugCuIndex<R>where
R: Clone,
impl<R> Clone for DebugTuIndex<R>where
R: Clone,
impl<R> Clone for UnitIndex<R>
impl<R> Clone for DebugLine<R>where
R: Clone,
impl<R> Clone for LineInstructions<R>
impl<R> Clone for LineSequence<R>
impl<R> Clone for DebugLoc<R>where
R: Clone,
impl<R> Clone for DebugLocLists<R>where
R: Clone,
impl<R> Clone for LocationListEntry<R>
impl<R> Clone for LocationLists<R>where
R: Clone,
impl<R> Clone for Expression<R>
impl<R> Clone for OperationIter<R>
impl<R> Clone for DebugPubNames<R>
impl<R> Clone for PubNamesEntry<R>
impl<R> Clone for PubNamesEntryIter<R>
impl<R> Clone for DebugPubTypes<R>
impl<R> Clone for PubTypesEntry<R>
impl<R> Clone for PubTypesEntryIter<R>
impl<R> Clone for DebugRanges<R>where
R: Clone,
impl<R> Clone for DebugRngLists<R>where
R: Clone,
impl<R> Clone for RangeLists<R>where
R: Clone,
impl<R> Clone for DebugLineStr<R>where
R: Clone,
impl<R> Clone for DebugStr<R>where
R: Clone,
impl<R> Clone for DebugStrOffsets<R>where
R: Clone,
impl<R> Clone for Attribute<R>
impl<R> Clone for DebugInfo<R>where
R: Clone,
impl<R> Clone for DebugInfoUnitHeadersIter<R>
impl<R> Clone for DebugTypes<R>where
R: Clone,
impl<R> Clone for DebugTypesUnitHeadersIter<R>
impl<R, A> Clone for UnwindContext<R, A>where
R: Clone + Reader,
A: Clone + UnwindContextStorage<R>,
<A as UnwindContextStorage<R>>::Stack: Clone,
impl<R, Offset> Clone for LineInstruction<R, Offset>
impl<R, Offset> Clone for gimli::read::op::Location<R, Offset>
impl<R, Offset> Clone for Operation<R, Offset>
impl<R, Offset> Clone for AttributeValue<R, Offset>
impl<R, Offset> Clone for ArangeHeader<R, Offset>
impl<R, Offset> Clone for CommonInformationEntry<R, Offset>
impl<R, Offset> Clone for FrameDescriptionEntry<R, Offset>
impl<R, Offset> Clone for CompleteLineProgram<R, Offset>
impl<R, Offset> Clone for FileEntry<R, Offset>
impl<R, Offset> Clone for IncompleteLineProgram<R, Offset>
impl<R, Offset> Clone for LineProgramHeader<R, Offset>
impl<R, Offset> Clone for Piece<R, Offset>
impl<R, Offset> Clone for UnitHeader<R, Offset>
impl<R, Program, Offset> Clone for LineRows<R, Program, Offset>where
R: Clone + Reader<Offset = Offset>,
Program: Clone + LineProgram<R, Offset>,
Offset: Clone + ReaderOffset,
impl<R, S> Clone for UnwindTableRow<R, S>where
R: Reader,
S: UnwindContextStorage<R>,
impl<T> !Clone for &mut Twhere
T: ?Sized,
Shared references can be cloned, but mutable references cannot!
impl<T> Clone for Bound<T>where
T: Clone,
impl<T> Clone for Option<T>where
T: Clone,
impl<T> Clone for Poll<T>where
T: Clone,
impl<T> Clone for UnitSectionOffset<T>where
T: Clone,
impl<T> Clone for DieReference<T>where
T: Clone,
impl<T> Clone for RawRngListEntry<T>where
T: Clone,
impl<T> Clone for *const Twhere
T: ?Sized,
impl<T> Clone for *mut Twhere
T: ?Sized,
impl<T> Clone for &Twhere
T: ?Sized,
Shared references can be cloned, but mutable references cannot!