Trait frame_support::dispatch::marker::Copy 1.0.0[−][src]
pub trait Copy: Clone { }
Expand description
Types whose values can be duplicated simply by copying bits.
By default, variable bindings have ‘move semantics.’ In other words:
#[derive(Debug)] struct Foo; let x = Foo; let y = x; // `x` has moved into `y`, and so cannot be used // println!("{:?}", x); // error: use of moved value
However, if a type implements Copy
, 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)] struct Foo; let x = Foo; let y = 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 you
are allowed to access x
after the assignment. Under the hood, both a copy and a move
can result in bits being copied in memory, although this is sometimes optimized away.
How can I implement Copy
?
There are two ways to implement Copy
on your type. The simplest is to use derive
:
#[derive(Copy, Clone)] struct MyStruct;
You can also implement Copy
and Clone
manually:
struct MyStruct; impl Copy for MyStruct { } impl Clone for MyStruct { fn clone(&self) -> MyStruct { *self } }
There is a small difference between the two: the derive
strategy will also place a Copy
bound on type parameters, which isn’t always desired.
What’s the difference between Copy
and Clone
?
Copies happen implicitly, for example as part of an assignment y = x
. The behavior of
Copy
is not overloadable; it is always a simple bit-wise copy.
Cloning is an explicit action, x.clone()
. The implementation of Clone
can
provide any type-specific behavior necessary to duplicate values safely. For example,
the implementation of Clone
for String
needs to copy the pointed-to string
buffer in the heap. A simple bitwise copy of String
values would merely copy the
pointer, leading to a double free down the line. For this reason, String
is Clone
but not Copy
.
Clone
is a supertrait of Copy
, so everything which is Copy
must also implement
Clone
. If a type is Copy
then its Clone
implementation only needs to return *self
(see the example above).
When can my type be Copy
?
A type can implement Copy
if all of its components implement Copy
. For example, this
struct can be Copy
:
#[derive(Copy, Clone)] struct Point { x: i32, y: i32, }
A struct can be Copy
, and i32
is Copy
, therefore Point
is eligible to be Copy
.
By contrast, consider
struct PointList { points: Vec<Point>, }
The struct PointList
cannot implement Copy
, because Vec<T>
is not Copy
. If we
attempt to derive a Copy
implementation, we’ll get an error:
the trait `Copy` may not be implemented for this type; field `points` does not implement `Copy`
Shared references (&T
) are also Copy
, so a type can be Copy
, even when it holds
shared references of types T
that are not Copy
. Consider the following struct,
which can implement Copy
, because it only holds a shared reference to our non-Copy
type PointList
from above:
#[derive(Copy, Clone)] struct PointListWrapper<'a> { point_list_ref: &'a PointList, }
When can’t my type be Copy
?
Some types can’t be copied safely. For example, copying &mut T
would create an aliased
mutable reference. Copying String
would duplicate responsibility for managing the
String
’s buffer, leading to a double free.
Generalizing the latter case, any type implementing Drop
can’t be Copy
, because it’s
managing some resource besides its own size_of::<T>
bytes.
If you try to implement Copy
on a struct or enum containing non-Copy
data, you will get
the error E0204.
When should my type be Copy
?
Generally speaking, if your type can implement Copy
, it should. Keep in mind, though,
that implementing Copy
is part of the public API of your type. If the type might become
non-Copy
in the future, it could be prudent to omit the Copy
implementation now, to
avoid a breaking API change.
Additional implementors
In addition to the implementors listed below,
the following types also implement Copy
:
- Function item types (i.e., the distinct types defined for each function)
- Function pointer types (e.g.,
fn() -> i32
) - Array types, for all sizes, if the item type also implements
Copy
(e.g.,[i32; 123456]
) - Tuple types, if each component also implements
Copy
(e.g.,()
,(i32, bool)
) - Closure types, if they capture no value from the environment
or if all such captured values implement
Copy
themselves. Note that variables captured by shared reference always implementCopy
(even if the referent doesn’t), while variables captured by mutable reference never implementCopy
.
Implementations on Foreign Types
Shared references can be copied, but mutable references cannot!
impl Copy for OptionBool
impl<'t> Copy for Match<'t>
impl<'t> Copy for Match<'t>
impl Copy for MatchKind
impl Copy for MatchKind
impl Copy for Flag
impl Copy for ClassBytesRange
impl Copy for Position
impl Copy for Utf8Range
impl Copy for Utf8Sequence
impl Copy for ClassSetBinaryOpKind
impl Copy for ClassUnicodeRange
impl Copy for Span
impl Copy for OnceState
impl Copy for WaitTimeoutResult
impl Copy for UnparkResult
impl Copy for RequeueOp
impl Copy for ParkResult
impl Copy for ParkToken
impl Copy for UnparkToken
impl Copy for FilterOp
impl Copy for glob64_t
impl Copy for DIR
impl Copy for Elf64_Ehdr
impl Copy for sockaddr_alg
impl Copy for ifaddrs
impl Copy for ipv6_mreq
impl Copy for pthread_mutex_t
impl Copy for Elf64_Chdr
impl Copy for _libc_fpstate
impl Copy for termios2
impl Copy for canfd_frame
impl Copy for statx
impl Copy for sockaddr_ll
impl Copy for tm
impl Copy for fpos_t
impl Copy for dirent64
impl Copy for statvfs
impl Copy for sigevent
impl Copy for genlmsghdr
impl Copy for input_keymap_entry
impl Copy for timespec
impl Copy for Elf64_Phdr
impl Copy for termios
impl Copy for nlmsghdr
impl Copy for __exit_status
impl Copy for ip_mreq_source
impl Copy for sigval
impl Copy for sockaddr_in6
impl Copy for statx_timestamp
impl Copy for shmid_ds
impl Copy for FILE
impl Copy for _libc_xmmreg
impl Copy for af_alg_iv
impl Copy for fanotify_response
impl Copy for Elf64_Sym
impl Copy for pthread_condattr_t
impl Copy for user_regs_struct
impl Copy for sockaddr
impl Copy for hostent
impl Copy for arpreq
impl Copy for uinput_ff_upload
impl Copy for utimbuf
impl Copy for uinput_user_dev
impl Copy for arphdr
impl Copy for itimerval
impl Copy for msginfo
impl Copy for linger
impl Copy for mq_attr
impl Copy for sigset_t
impl Copy for fd_set
impl Copy for __c_anonymous_sockaddr_can_tp
impl Copy for input_event
impl Copy for statvfs64
impl Copy for sysinfo
impl Copy for posix_spawnattr_t
impl Copy for sockaddr_vm
impl Copy for uinput_abs_setup
impl Copy for protoent
impl Copy for itimerspec
impl Copy for ip_mreqn
impl Copy for packet_mreq
impl Copy for nlmsgerr
impl Copy for siginfo_t
impl Copy for pthread_rwlock_t
impl Copy for cpu_set_t
impl Copy for rlimit
impl Copy for glob_t
impl Copy for inotify_event
impl Copy for sockaddr_nl
impl Copy for uinput_ff_erase
impl Copy for Elf32_Phdr
impl Copy for statfs
impl Copy for sigaction
impl Copy for nl_pktinfo
impl Copy for __c_anonymous_sockaddr_can_j1939
impl Copy for sockaddr_storage
impl Copy for user
impl Copy for spwd
impl Copy for ntptimeval
impl Copy for Elf32_Sym
impl Copy for ff_periodic_effect
impl Copy for Elf32_Shdr
impl Copy for cmsghdr
impl Copy for user_fpregs_struct
impl Copy for in_pktinfo
impl Copy for input_absinfo
impl Copy for ff_rumble_effect
impl Copy for utsname
impl Copy for ip_mreq
impl Copy for tms
impl Copy for iovec
impl Copy for pthread_attr_t
impl Copy for sock_extended_err
impl Copy for Elf32_Ehdr
impl Copy for ff_condition_effect
impl Copy for _libc_fpxreg
impl Copy for msghdr
impl Copy for ff_constant_effect
impl Copy for passwd
impl Copy for sembuf
impl Copy for ff_ramp_effect
impl Copy for mcontext_t
impl Copy for flock64
impl Copy for rusage
impl Copy for can_frame
impl Copy for rtentry
impl Copy for ucontext_t
impl Copy for dqblk
impl Copy for timex
impl Copy for fanotify_event_metadata
impl Copy for sched_param
impl Copy for sockaddr_can
impl Copy for timezone
impl Copy for sockaddr_un
impl Copy for group
impl Copy for signalfd_siginfo
impl Copy for epoll_event
impl Copy for stat
impl Copy for ff_replay
impl Copy for in6_pktinfo
impl Copy for in6_rtmsg
impl Copy for timeval
impl Copy for fpos64_t
impl Copy for rlimit64
impl Copy for uinput_setup
impl Copy for ff_effect
impl Copy for lconv
impl Copy for addrinfo
impl Copy for ipc_perm
impl Copy for statfs64
impl Copy for Dl_info
impl Copy for in6_addr
impl Copy for arpreq_old
impl Copy for sem_t
impl Copy for aiocb
impl Copy for can_filter
impl Copy for mntent
impl Copy for input_mask
impl Copy for pthread_mutexattr_t
impl Copy for nl_mmap_hdr
impl Copy for regex_t
impl Copy for pthread_cond_t
impl Copy for ucred
impl Copy for arpd_request
impl Copy for ff_envelope
impl Copy for dl_phdr_info
impl Copy for mallinfo
impl Copy for winsize
impl Copy for Elf32_Chdr
impl Copy for ff_trigger
impl Copy for pollfd
impl Copy for dirent
impl Copy for regmatch_t
impl Copy for utmpx
impl Copy for __timeval
impl Copy for stack_t
impl Copy for fsid_t
impl Copy for nl_mmap_req
impl Copy for stat64
impl Copy for servent
impl Copy for sockaddr_in
impl Copy for pthread_rwlockattr_t
impl Copy for mmsghdr
impl Copy for __c_anonymous_sockaddr_can_can_addr
impl Copy for flock
impl Copy for posix_spawn_file_actions_t
impl Copy for max_align_t
impl Copy for nlattr
impl Copy for in_addr
impl Copy for msqid_ds
impl Copy for Elf64_Shdr
impl Copy for input_id
impl Copy for if_nameindex
impl Copy for BigEndian
impl Copy for LittleEndian
impl Copy for Infix
impl Copy for Suffix
impl Copy for Colour
impl Copy for Style
impl Copy for Prefix
impl Copy for ValueType
impl Copy for F32
impl Copy for RuntimeValue
impl Copy for F64
impl Copy for VarInt64
impl Copy for TableType
impl Copy for Local
impl Copy for GlobalType
impl Copy for VarInt7
impl Copy for VarInt32
impl Copy for ResizableLimits
impl Copy for ValueType
impl Copy for Uint8
impl Copy for BlockType
impl Copy for RelocationEntry
impl Copy for Uint32
impl Copy for Internal
impl Copy for MemoryType
impl Copy for ImportCountType
impl Copy for VarUint64
impl Copy for TableElementType
impl Copy for External
impl Copy for VarUint1
impl Copy for Uint64
impl Copy for Func
impl Copy for VarUint7
impl Copy for VarUint32
impl Copy for StackValueType
impl Copy for StartedWith
impl Copy for Pages
impl Copy for Pages
impl Copy for Bytes
impl Copy for Words
impl Copy for Words
impl Copy for Errno
impl Copy for U512
impl Copy for H512
impl Copy for H128
impl Copy for U256
impl Copy for H160
impl Copy for U128
impl Copy for H256
impl Copy for FromHexError
impl<X> Copy for Uniform<X> where
X: Copy + SampleUniform,
<X as SampleUniform>::Sampler: Copy,
impl Copy for vec512_storage
impl Copy for vec256_storage
impl Copy for YesS3
impl Copy for NoNI
impl Copy for vec128_storage
impl Copy for NoS3
impl Copy for YesS4
impl Copy for NoS4
impl Copy for YesA1
impl Copy for NoA1
impl Copy for NoA2
impl Copy for YesNI
impl Copy for YesA2
impl Copy for FromStrRadixErrKind
impl<T, N> Copy for GenericArray<T, N> where
T: Copy,
N: ArrayLength<T>,
<N as ArrayLength<T>>::ArrayType: Copy,
impl Copy for Z0
impl Copy for Less
impl Copy for UTerm
impl Copy for B1
impl Copy for Equal
impl Copy for B0
impl Copy for Greater
impl Copy for ATerm
impl Copy for ZeroPadding
impl Copy for UnpadError
impl Copy for Iso7816
impl Copy for AnsiX923
impl Copy for NoPadding
impl Copy for Pkcs7
impl Copy for PadError
impl Copy for InvalidOutputSize
impl<X> Copy for Uniform<X> where
X: Copy + SampleUniform,
<X as SampleUniform>::Sampler: Copy,
impl Copy for Language
impl Copy for MnemonicType
impl Copy for InvalidKeyLength
impl Copy for MacError
impl Copy for RecoveryId
impl Copy for InvalidOutputSize
impl<T, N> Copy for GenericArray<T, N> where
T: Copy,
N: ArrayLength<T>,
<N as ArrayLength<T>>::ArrayType: Copy,
impl Copy for InvalidKeyLength
impl Copy for MacError
impl Copy for Choice
impl Copy for UnpadError
impl Copy for PadError
impl Copy for u32x4
impl Copy for u64x2
impl Copy for Error
impl Copy for ECQVCertPublic
impl Copy for PublicKey
impl Copy for MultiSignatureStage
impl Copy for ECQVCertSecret
impl Copy for SignatureError
impl Copy for ChainCode
impl Copy for Cosignature
impl Copy for Signature
impl Copy for RistrettoBoth
impl Copy for Commitment
impl Copy for VRFOutput
impl Copy for PublicKey
impl Copy for Blake2bResult
impl Copy for Blake2sResult
impl Copy for XxHash64
impl Copy for XxHash32
impl Copy for Aborted
impl Copy for PollNext
impl Copy for Canceled
impl<'a> Copy for NodeHandle<'a>
impl<'a> Copy for NibbleSlice<'a>
impl<T> Copy for MemCounter<T>
impl<T> Copy for NoopTracker<T>
impl Copy for SectionId
impl<'abbrev, 'entry, 'unit, R> Copy for AttrsIter<'abbrev, 'entry, 'unit, R> where
R: Copy + Reader,
impl Copy for DwAddr
impl Copy for DwDs
impl Copy for FileEntryFormat
impl<R, Offset> Copy for Location<R, Offset> where
R: Copy + Reader<Offset = Offset>,
Offset: Copy + ReaderOffset,
impl Copy for AttributeSpecification
impl<R, Offset> Copy for AttributeValue<R, Offset> where
R: Copy + Reader<Offset = Offset>,
Offset: Copy + ReaderOffset,
impl Copy for Error
impl Copy for Format
impl Copy for DwUt
impl Copy for LineRow
impl Copy for DwMacro
impl Copy for DwAccess
impl Copy for Value
impl Copy for Encoding
impl Copy for DwAte
impl Copy for DebugTypeSignature
impl Copy for DwLns
impl<R, Offset> Copy for Piece<R, Offset> where
R: Copy + Reader<Offset = Offset>,
Offset: Copy + ReaderOffset,
impl Copy for DwId
impl Copy for DwInl
impl Copy for Arm
impl Copy for DwChildren
impl Copy for ValueType
impl Copy for DwTag
impl Copy for DwEhPe
impl<R, Offset> Copy for FileEntry<R, Offset> where
R: Copy + Reader<Offset = Offset>,
Offset: Copy + ReaderOffset,
impl Copy for DwOp
impl Copy for DwLnct
impl Copy for DwIdx
impl Copy for ReaderOffsetId
impl Copy for DwVirtuality
impl Copy for ColumnType
impl Copy for DwCc
impl Copy for LittleEndian
impl Copy for X86
impl Copy for Pointer
impl Copy for DwLle
impl Copy for DwVis
impl Copy for Range
impl Copy for DwEnd
impl Copy for DwoId
impl Copy for DwForm
impl Copy for Augmentation
impl Copy for DwLne
impl Copy for DwarfFileType
impl<R, Offset> Copy for Operation<R, Offset> where
R: Copy + Reader<Offset = Offset>,
Offset: Copy + ReaderOffset,
impl Copy for Register
impl Copy for DwDsc
impl Copy for DwDefaulted
impl Copy for RunTimeEndian
impl Copy for DwLang
impl Copy for DwRle
impl Copy for DwOrd
impl Copy for BigEndian
impl<R, Offset> Copy for LineInstruction<R, Offset> where
R: Copy + Reader<Offset = Offset>,
Offset: Copy + ReaderOffset,
impl Copy for LineEncoding
impl<R, Offset> Copy for UnitHeader<R, Offset> where
R: Copy + Reader<Offset = Offset>,
Offset: Copy + ReaderOffset,
impl Copy for DwAt
impl Copy for X86_64
impl Copy for DwCfa
impl Copy for ImageCoffSymbolsHeader
impl<'data> Copy for StringTable<'data>
impl<'data> Copy for CompressedData<'data>
impl Copy for ImageImportByName
impl Copy for ImageCor20Header
impl Copy for ImageNtHeaders64
impl Copy for ImageDynamicRelocation64
impl Copy for ImageResourceDataEntry
impl Copy for ImageOptionalHeader32
impl Copy for CompressionFormat
impl<'data, Elf> Copy for SymbolTable<'data, Elf> where
Elf: Copy + FileHeader,
<Elf as FileHeader>::Sym: Copy,
impl<'data, 'file> Copy for CoffSymbol<'data, 'file> where
'data: 'file,
impl Copy for AnonObjectHeaderV2
impl Copy for RelocationEncoding
impl Copy for Header
impl Copy for ImagePrologueDynamicRelocationHeader
impl Copy for LittleEndian
impl Copy for SymbolKind
impl Copy for ImageArchiveMemberHeader
impl Copy for ImageEpilogueDynamicRelocationHeader
impl Copy for ImageLoadConfigDirectory32
impl<'data> Copy for Export<'data>
impl Copy for Endianness
impl Copy for ImageRelocation
impl Copy for ImageExportDirectory
impl Copy for ScatteredRelocationInfo
impl Copy for ImageAlpha64RuntimeFunctionEntry
impl Copy for ImageArmRuntimeFunctionEntry
impl Copy for Architecture
impl Copy for ImageFunctionEntry64
impl<'data, 'file, Elf> Copy for ElfSymbolTable<'data, 'file, Elf> where
'data: 'file,
Elf: Copy + FileHeader,
<Elf as FileHeader>::Endian: Copy,
impl Copy for FileFlags
impl Copy for SymbolIndex
impl<'data> Copy for Import<'data>
impl Copy for ImageTlsDirectory64
impl Copy for SymbolScope
impl Copy for ImageAuxSymbolWeak
impl Copy for ImageSymbol
impl Copy for ImageLoadConfigDirectory64
impl Copy for Guid
impl Copy for BigEndian
impl Copy for ImageOptionalHeader64
impl Copy for ImageDynamicRelocation64V2
impl Copy for ImageDebugDirectory
impl Copy for ImageEnclaveConfig32
impl<'data, Elf> Copy for SectionTable<'data, Elf> where
Elf: Copy + FileHeader,
<Elf as FileHeader>::SectionHeader: Copy,
impl Copy for ImageAuxSymbolFunctionBeginEnd
impl Copy for ImageHotPatchBase
impl<'data> Copy for Bytes<'data>
impl Copy for SectionIndex
impl Copy for ImageLoadConfigCodeIntegrity
impl Copy for NonPagedDebugInfo
impl Copy for ImageSectionHeader
impl Copy for AnonObjectHeader
impl Copy for ArchiveKind
impl Copy for SectionKind
impl<'data, 'file> Copy for CoffSymbolTable<'data, 'file> where
'data: 'file,
impl Copy for ImageEnclaveConfig64
impl Copy for ImageResourceDirectoryEntry
impl Copy for RelocationKind
impl Copy for Ident
impl Copy for SymbolSection
impl Copy for ImageAuxSymbolTokenDef
impl Copy for ImageEnclaveImport
impl Copy for FatHeader
impl Copy for ImageAuxSymbolFunction
impl Copy for RelocationTarget
impl Copy for ImageDynamicRelocationTable
impl Copy for ImportObjectHeader
impl Copy for Error
impl Copy for ImageBoundForwarderRef
impl Copy for ImageNtHeaders32
impl Copy for ImageSymbolBytes
impl Copy for ImageDynamicRelocation32
impl Copy for ImageLinenumber
impl Copy for AnonObjectHeaderBigobj
impl Copy for ImageTlsDirectory32
impl Copy for ImageHotPatchHashes
impl Copy for ImageOs2Header
impl Copy for BinaryFormat
impl Copy for ImageSeparateDebugHeader
impl Copy for ImageSymbolEx
impl<'data> Copy for SectionTable<'data>
impl Copy for ImageVxdHeader
impl Copy for ImageResourceDirectoryString
impl Copy for ImageHotPatchInfo
impl Copy for ImageResourceDirectory
impl Copy for ImageDebugMisc
impl<'data, 'file, Mach> Copy for MachOSymbol<'data, 'file, Mach> where
Mach: Copy + MachHeader,
<Mach as MachHeader>::Nlist: Copy,
impl Copy for ImageAuxSymbolCrc
impl Copy for ImageDataDirectory
impl Copy for SectionFlags
impl Copy for ImageResourceDirStringU
impl Copy for FatArch32
impl Copy for AddressSize
impl Copy for ImageAuxSymbolSection
impl Copy for ImageAlphaRuntimeFunctionEntry
impl Copy for ImageFileHeader
impl<'data, Mach> Copy for SymbolTable<'data, Mach> where
Mach: Copy + MachHeader,
<Mach as MachHeader>::Nlist: Copy,
impl Copy for ImageRomHeaders
impl Copy for ComdatKind
impl Copy for ImageBaseRelocation
impl Copy for ImageDelayloadDescriptor
impl Copy for ImageFunctionEntry
impl Copy for FatArch64
impl Copy for ImageArm64RuntimeFunctionEntry
impl<'data> Copy for ObjectMapEntry<'data>
impl Copy for ImageRomOptionalHeader
impl Copy for RelocationInfo
impl Copy for ImageImportDescriptor
impl Copy for ImageDosHeader
impl<'data, 'file, Elf> Copy for ElfSymbol<'data, 'file, Elf> where
'data: 'file,
Elf: Copy + FileHeader,
<Elf as FileHeader>::Endian: Copy,
<Elf as FileHeader>::Sym: Copy,
impl Copy for ImageDynamicRelocation32V2
impl<'data> Copy for SymbolMapName<'data>
impl<'data, 'file, Mach> Copy for MachOSymbolTable<'data, 'file, Mach> where
Mach: Copy + MachHeader,
impl Copy for ImageRuntimeFunctionEntry
impl Copy for ImageArchitectureEntry
impl Copy for ImageSymbolExBytes
impl Copy for ImageBoundImportDescriptor
impl Copy for DataFormat
impl Copy for MZFlush
impl Copy for MZStatus
impl Copy for TDEFLStatus
impl Copy for TDEFLFlush
impl Copy for CompressionLevel
impl Copy for TINFLStatus
impl Copy for MZError
impl Copy for CompressionStrategy
impl Copy for StreamResult
impl<Info> Copy for DispatchErrorWithPostInfo<Info> where
Info: Copy + Eq + PartialEq<Info> + Clone + Encode + Decode + Printable,