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,
}
§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:
// 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.
§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§
1.0.0 · 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 ConversionError
impl Clone for gstd::errors::CoreError
impl Clone for gstd::errors::Error
impl Clone for ErrorReplyReason
impl Clone for ExecutionError
impl Clone for ExtError
impl Clone for MemoryError
impl Clone for MessageError
impl Clone for ReplyCode
impl Clone for ReservationError
impl Clone for SignalCode
impl Clone for SimpleExecutionError
impl Clone for SimpleProgramCreationError
impl Clone for SuccessReplyReason
impl Clone for UsageError
impl Clone for AsciiChar
impl Clone for gstd::prelude::cmp::Ordering
impl Clone for TryReserveErrorKind
impl Clone for gstd::prelude::collections::hashbrown::TryReserveError
impl Clone for Infallible
impl Clone for gstd::prelude::fmt::Alignment
impl Clone for FpCategory
impl Clone for IntErrorKind
impl Clone for SearchStep
impl Clone for IpAddr
impl Clone for Ipv6MulticastScope
impl Clone for SocketAddr
impl Clone for core::sync::atomic::Ordering
impl Clone for hex::error::FromHexError
impl Clone for bool
impl Clone for char
impl Clone for f16
impl Clone for f32
impl Clone for f64
impl Clone for f128
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 gstd::errors::CodecError
impl Clone for ErrorReplyPayload
impl Clone for SyscallError
impl Clone for gstd::msg::MessageHandle
impl Clone for ActorId
impl Clone for CodeId
impl Clone for EnvVars
impl Clone for GasMultiplier
impl Clone for MessageId
impl Clone for Percent
impl Clone for Reservation
impl Clone for ReservationId
impl Clone for Reservations
impl Clone for MetaType
impl Clone for TypeId
impl Clone for TryFromSliceError
impl Clone for gstd::prelude::ascii::EscapeDefault
impl Clone for CharTryFromError
impl Clone for DecodeUtf16Error
impl Clone for gstd::prelude::char::EscapeDebug
impl Clone for gstd::prelude::char::EscapeDefault
impl Clone for gstd::prelude::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 gstd::prelude::collections::TryReserveError
impl Clone for CString
impl Clone for FromBytesUntilNulError
impl Clone for FromBytesWithNulError
impl Clone for FromVecWithNulError
impl Clone for IntoStringError
impl Clone for NulError
impl Clone for gstd::prelude::fmt::Error
impl Clone for SipHasher
impl Clone for PhantomPinned
impl Clone for Assume
impl Clone for ParseFloatError
impl Clone for ParseIntError
impl Clone for TryFromIntError
impl Clone for RangeFull
impl Clone for gstd::prelude::ptr::Alignment
impl Clone for ParseBoolError
impl Clone for Utf8Error
impl Clone for FromUtf8Error
impl Clone for gstd::prelude::Box<str>
impl Clone for gstd::prelude::Box<CStr>
impl Clone for String
impl Clone for LocalWaker
impl Clone for RawWakerVTable
impl Clone for Waker
impl Clone for Duration
impl Clone for TryFromFloatSecsError
impl Clone for alloc::alloc::Global
impl Clone for Layout
impl Clone for LayoutError
impl Clone for core::alloc::AllocError
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 Ipv4Addr
impl Clone for Ipv6Addr
impl Clone for AddrParseError
impl Clone for SocketAddrV4
impl Clone for SocketAddrV6
impl Clone for Choice
impl Clone for ATerm
impl Clone for B0
impl Clone for B1
impl Clone for Z0
impl Clone for Equal
impl Clone for Greater
impl Clone for Less
impl Clone for UTerm
impl Clone for AHasher
impl Clone for AbortHandle
impl Clone for Aborted
impl Clone for AllocError
impl Clone for Alphabet
impl Clone for BigEndian
impl Clone for Blake2bVarCore
impl Clone for Blake2sVarCore
impl Clone for Box<str>
impl Clone for Box<CStr>
impl Clone for Canceled
impl Clone for Eager
impl Clone for Error
impl Clone for Error
impl Clone for Error
impl Clone for Error
impl Clone for Error
impl Clone for FromHexError
impl Clone for FromStrRadixErrKind
impl Clone for Global
impl Clone for H128
impl Clone for H160
impl Clone for H256
impl Clone for H384
impl Clone for H512
impl Clone for H768
impl Clone for HashWithValue
impl Clone for InvalidBufferSize
impl Clone for InvalidLength
impl Clone for InvalidOutputSize
impl Clone for Lazy
impl Clone for LittleEndian
impl Clone for MacError
impl Clone for MessageHandle
impl Clone for MetaForm
impl Clone for NonZeroU256
impl Clone for OptionBool
impl Clone for PollNext
impl Clone for PortableForm
impl Clone for PortableRegistry
impl Clone for PortableType
impl Clone for RandomState
impl Clone for TruncSide
impl Clone for TypeDefPrimitive
impl Clone for U128
impl Clone for U256
impl Clone for U512
impl<'a> Clone for gstd::prelude::ffi::c_str::Bytes<'a>
impl<'a> Clone for Arguments<'a>
impl<'a> Clone for Location<'a>
impl<'a> Clone for EscapeAscii<'a>
impl<'a> Clone for CharSearcher<'a>
impl<'a> Clone for gstd::prelude::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 gstd::prelude::str::EscapeDebug<'a>
impl<'a> Clone for gstd::prelude::str::EscapeDefault<'a>
impl<'a> Clone for gstd::prelude::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> Clone for Source<'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 gstd::prelude::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 gstd::prelude::str::Split<'a, P>
impl<'a, P> Clone for gstd::prelude::str::SplitInclusive<'a, P>
impl<'a, P> Clone for SplitN<'a, P>
impl<'a, P> Clone for SplitTerminator<'a, P>
impl<'a, T> Clone for RChunksExact<'a, T>
impl<'a, T> Clone for CompactRef<'a, T>where
T: Clone,
impl<'a, T> Clone for Ptr<'a, T>where
T: ?Sized,
impl<'a, T> Clone for Symbol<'a, T>where
T: Clone + 'a,
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<'f> Clone for VaListImpl<'f>
impl<A> Clone for gstd::prelude::iter::Repeat<A>where
A: Clone,
impl<A> Clone for RepeatN<A>where
A: Clone,
impl<A> Clone for gstd::prelude::option::IntoIter<A>where
A: Clone,
impl<A> Clone for gstd::prelude::option::Iter<'_, A>
impl<A> Clone for IterRange<A>where
A: Clone,
impl<A> Clone for IterRangeFrom<A>where
A: Clone,
impl<A> Clone for IterRangeInclusive<A>where
A: Clone,
impl<A, B> Clone for Chain<A, B>
impl<A, B> Clone for Zip<A, B>
impl<A, B> Clone for Either<A, B>
impl<B> Clone for Cow<'_, B>
impl<B, C> Clone for ControlFlow<B, C>
impl<BlockSize, Kind> Clone for BlockBuffer<BlockSize, Kind>
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 gstd::prelude::iter::RepeatWith<F>where
F: Clone,
impl<F> Clone for OptionFuture<F>where
F: Clone,
impl<F> Clone for RepeatWith<F>where
F: Clone,
impl<H> Clone for BuildHasherDefault<H>
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> Clone for FromIter<I>where
I: Clone,
impl<I> Clone for Iter<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 gstd::prelude::iter::ArrayChunks<I, N>
impl<Idx> Clone for gstd::prelude::ops::Range<Idx>where
Idx: Clone,
impl<Idx> Clone for gstd::prelude::ops::RangeFrom<Idx>where
Idx: Clone,
impl<Idx> Clone for gstd::prelude::ops::RangeInclusive<Idx>where
Idx: Clone,
impl<Idx> Clone for RangeTo<Idx>where
Idx: Clone,
impl<Idx> Clone for RangeToInclusive<Idx>where
Idx: Clone,
impl<Idx> Clone for core::range::Range<Idx>where
Idx: Clone,
impl<Idx> Clone for core::range::RangeFrom<Idx>where
Idx: Clone,
impl<Idx> Clone for core::range::RangeInclusive<Idx>where
Idx: Clone,
impl<K> Clone for gstd::prelude::collections::hash_set::Iter<'_, K>
impl<K, V> Clone for gstd::prelude::collections::btree_map::Cursor<'_, K, V>
impl<K, V> Clone for gstd::prelude::collections::btree_map::Iter<'_, K, V>
impl<K, V> Clone for gstd::prelude::collections::btree_map::Keys<'_, K, V>
impl<K, V> Clone for gstd::prelude::collections::btree_map::Range<'_, K, V>
impl<K, V> Clone for gstd::prelude::collections::btree_map::Values<'_, K, V>
impl<K, V> Clone for gstd::prelude::collections::hash_map::Iter<'_, K, V>
impl<K, V> Clone for gstd::prelude::collections::hash_map::Keys<'_, K, V>
impl<K, V> Clone for gstd::prelude::collections::hash_map::Values<'_, K, V>
impl<K, V, A> Clone for BTreeMap<K, V, A>
impl<K, V, S, A> Clone for HashMap<K, V, S, A>
impl<OutSize> Clone for Blake2bMac<OutSize>
impl<OutSize> Clone for Blake2sMac<OutSize>
impl<Ptr> Clone for Pin<Ptr>where
Ptr: Clone,
impl<S> Clone for PollImmediate<S>where
S: Clone,
impl<Si, F> Clone for SinkMapErr<Si, F>
impl<Si, Item, U, Fut, F> Clone for With<Si, Item, U, Fut, F>
impl<T> !Clone for &mut Twhere
T: ?Sized,
Shared references can be cloned, but mutable references cannot!
impl<T> Clone for Option<T>where
T: Clone,
impl<T> Clone for Bound<T>where
T: Clone,
impl<T> Clone for Poll<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!