Copy

From Rust Community Wiki

The Copy trait is a marker trait for any type that can be copied bit-wise instead of executing the clone function.

Implicit Behavior[edit]

The Copy trait changes the behavior of the = assign operator from changing Ownership to copying. In this example, the type that does not implement Copy can only be assigned from once, since it is moved, but the type that implements Copy is allowed to be assigned from twice, because copying it does not invalidate the original variable.

#[derive(Clone)]
struct OwnedType;

#[derive(Clone, Copy)]
struct CopiedType;

let first_owned = OwnedType;
let second_owned = first_owned;
//let third_owned = first_owned; //ERROR

let first_copied = CopiedType;
let second_copied = first_copied;
let third_copied = first_copied;


Other operations that change Ownership are also affected, such as parameter passing in function calls. The Copy trait does not change the behavior of Borrowing, so taking more than one mutable reference to a type that implements Copy will still fail to compile.

Relationship with Clone[edit]

Copy is declared as a subtrait of Clone. Any type that implements Copy must also implement Clone. Typically, this is done with derive, but this is not required, and there is no promise that Clone::clone will actually be a bitwise copy.

struct ManualCopyAndClone;

impl Copy for ManualCopyAndClone {}

impl Clone for ManualCopyAndClone {
    fn clone(&self) -> Self {
        panic!("Copy is implemented, yet Clone is not allowed.")
    }
}


Doing this annoys a lot of people and is usually considered a bad idea.

Relationship with Drop[edit]

The Copy and Drop traits contradict each other.

struct DropCopy;

impl Copy for DropCopy {}

//ERROR
//impl Drop for DropCopy {
//    fn drop(&mut self) {}
//}


Structural requirements[edit]

For a struct or enum to implement Copy, any fields must implement Copy. Unlike Send and Sync, there is no direct way to override this (it can be indirectly overridden using mem::transmute to convert the non-Copy data to something that does implement Copy, such as [u8; mem::size_of::<Data>()]).