pub trait Copy:Clone { }Expand description
Types whose values can be duplicated simply by copying bits.
By default, variable bindings have ‘move semantics.’ In otherwords:
#[derive(Debug)]structFoo;letx = Foo;lety = x;// `x` has moved into `y`, and so cannot be used// println!("{x:?}"); // error: use of moved valueHowever, if a type implementsCopy, it instead has ‘copy semantics’:
// We can derive a `Copy` implementation. `Clone` is also required, as it's// a supertrait of `Copy`.#[derive(Debug, Copy, Clone)]structFoo;letx = Foo;lety = x;// `y` is a copy of `x`println!("{x:?}");// A-OK!It’s important to note that in these two examples, the only difference is whether youare allowed to accessx after the assignment. Under the hood, both a copy and a movecan result in bits being copied in memory, although this is sometimes optimized away.
§How can I implementCopy?
There are two ways to implementCopy on your type. The simplest is to usederive:
You can also implementCopy andClone manually:
There is a small difference between the two. Thederive strategy will also place aCopybound on type parameters:
This isn’t always desired. For example, shared references (&T) can be copied regardless ofwhetherT isCopy. Likewise, a generic struct containing markers such asPhantomDatacould potentially be duplicated with a bit-wise copy.
§What’s the difference betweenCopy andClone?
Copies happen implicitly, for example as part of an assignmenty = x. The behavior ofCopy is not overloadable; it is always a simple bit-wise copy.
Cloning is an explicit action,x.clone(). The implementation ofClone canprovide any type-specific behavior necessary to duplicate values safely. For example,the implementation ofClone forString needs to copy the pointed-to stringbuffer in the heap. A simple bitwise copy ofString values would merely copy thepointer, leading to a double free down the line. For this reason,String isClonebut notCopy.
Clone is a supertrait ofCopy, so everything which isCopy must also implementClone. If a type isCopy then itsClone implementation only needs to return*self(see the example above).
§When can my type beCopy?
A type can implementCopy if all of its components implementCopy. For example, thisstruct can beCopy:
A struct can beCopy, andi32 isCopy, thereforePoint is eligible to beCopy.By contrast, consider
The structPointList cannot implementCopy, becauseVec<T> is notCopy. If weattempt to derive aCopy implementation, we’ll get an error:
the trait `Copy` cannot be implemented for this type; field `points` does not implement `Copy`Shared references (&T) are alsoCopy, so a type can beCopy, even when it holdsshared references of typesT that arenotCopy. Consider the following struct,which can implementCopy, because it only holds ashared reference to our non-CopytypePointList from above:
§Whencan’t my type beCopy?
Some types can’t be copied safely. For example, copying&mut T would create an aliasedmutable reference. CopyingString would duplicate responsibility for managing theString’s buffer, leading to a double free.
Generalizing the latter case, any type implementingDrop can’t beCopy, because it’smanaging some resource besides its ownsize_of::<T> bytes.
If you try to implementCopy on a struct or enum containing non-Copy data, you will getthe errorE0204.
§Whenshould my type beCopy?
Generally speaking, if your typecan implementCopy, it should. Keep in mind, though,that implementingCopy is part of the public API of your type. If the type might becomenon-Copy in the future, it could be prudent to omit theCopy implementation now, toavoid a breaking API change.
§Additional implementors
In addition to theimplementors listed below,the following types also implementCopy:
- 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 environmentor if all such captured values implement
Copythemselves.Note that variables captured by shared reference always implementCopy(even if the referent doesn’t),while variables captured by mutable reference never implementCopy.
Dyn Compatibility§
This trait isnotdyn compatible.
In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.
Implementors§
implCopy forAsciiChar
implCopy for std::cmp::Ordering
implCopy forInfallible
implCopy forFromBytesWithNulError
implCopy for std::fmt::Alignment
implCopy forDebugAsHex
implCopy forSign
implCopy forErrorKind
implCopy forSeekFrom
implCopy forIpAddr
implCopy forIpv6MulticastScope
implCopy forShutdown
implCopy forSocketAddr
implCopy forFpCategory
implCopy forIntErrorKind
implCopy forBacktraceStyle
implCopy forSearchStep
implCopy for std::sync::atomic::Ordering
implCopy forRecvTimeoutError
implCopy forTryRecvError
implCopy forbool
implCopy forchar
implCopy forf16
implCopy forf32
implCopy forf64
implCopy forf128
implCopy fori8
implCopy fori16
implCopy fori32
implCopy fori64
implCopy fori128
implCopy forisize
implCopy for!
implCopy foru8
implCopy foru16
implCopy foru32
implCopy foru64
implCopy foru128
implCopy forusize
implCopy forCpuidResult
implCopy for__m128
implCopy for__m128bh
implCopy for__m128d
implCopy for__m128h
implCopy for__m128i
implCopy for__m256
implCopy for__m256bh
implCopy for__m256d
implCopy for__m256h
implCopy for__m256i
implCopy for__m512
implCopy for__m512bh
implCopy for__m512d
implCopy for__m512h
implCopy for__m512i
implCopy forbf16
implCopy forAllocError
implCopy forGlobal
implCopy forLayout
implCopy forSystem
implCopy forTypeId
implCopy forTryFromSliceError
implCopy forCharTryFromError
implCopy forTryFromCharError
implCopy forError
implCopy forFormattingOptions
implCopy forFileTimes
implCopy forFileType
implCopy forEmpty
implCopy forSink
implCopy forAssume
implCopy forIpv4Addr
implCopy forIpv6Addr
implCopy forSocketAddrV4
implCopy forSocketAddrV6
implCopy forTryFromIntError
implCopy forRangeFull
implCopy forUCred
implCopy forExitCode
implCopy forExitStatus
implCopy forExitStatusError
implCopy for std::ptr::Alignment
implCopy forDefaultRandomSource
implCopy forUtf8Error
implCopy forRecvError
implCopy forWaitTimeoutResult
implCopy forRawWakerVTable
implCopy forAccessError
implCopy forThreadId
implCopy forDuration
implCopy forInstant
implCopy forSystemTime
implCopy forPhantomPinned
impl<'a>Copy forComponent<'a>
impl<'a>Copy forPrefix<'a>
impl<'a>Copy forUtf8Pattern<'a>
impl<'a>Copy forArguments<'a>
impl<'a>Copy forIoSlice<'a>
impl<'a>Copy forLocation<'a>
impl<'a>Copy forAncestors<'a>
impl<'a>Copy forPrefixComponent<'a>
impl<'a>Copy forPhantomContravariantLifetime<'a>
impl<'a>Copy forPhantomCovariantLifetime<'a>
impl<'a>Copy forPhantomInvariantLifetime<'a>
impl<'a, T, const N:usize>Copy forArrayWindows<'a, T, N>where T:Copy + 'a,
impl<'fd>Copy forBorrowedFd<'fd>
target_os=trusty or WASI ortarget_os=motor only.impl<'handle>Copy forBorrowedHandle<'handle>
impl<'socket>Copy forBorrowedSocket<'socket>
impl<B, C>Copy forControlFlow<B, C>
impl<Dyn>Copy forDynMetadata<Dyn>where Dyn: ?Sized,
impl<F>Copy forRepeatWith<F>where F:Copy,
impl<Idx>Copy forRangeTo<Idx>where Idx:Copy,
impl<Idx>Copy for std::ops::RangeToInclusive<Idx>where Idx:Copy,
impl<Idx>Copy forRange<Idx>where Idx:Copy,
impl<Idx>Copy forRangeFrom<Idx>where Idx:Copy,
impl<Idx>Copy forRangeInclusive<Idx>where Idx:Copy,
impl<Idx>Copy for std::range::RangeToInclusive<Idx>where Idx:Copy,
impl<Ptr>Copy forPin<Ptr>where Ptr:Copy,
impl<T>Copy forBound<T>where T:Copy,
impl<T>Copy forOption<T>where T:Copy,
impl<T>Copy forPoll<T>where T:Copy,
impl<T>Copy for*const Twhere T: ?Sized,
impl<T>Copy for*mut Twhere T: ?Sized,
impl<T>Copy for&Twhere T: ?Sized,
Shared references can be copied, but mutable referencescannot!