What is the difference between Copy and Clone?

This problem , apparently, implies it only as an implementation detail ( memcpy vs ???), but I cannot find any explicit description of the differences.

+43
rust
Jun 23 '15 at 20:31
source share
2 answers

Clone designed for arbitrary duplication: the Clone implementation for type T can perform arbitrarily complex operations necessary to create a new T This is a normal feature (different from the prelude), so it should be used as a regular attribute, with method calls, etc. The Copy characteristic represents values ​​that can be safely duplicated using memcpy : things like remapping and passing an argument by value to a function are always memcpy s, and therefore, for Copy types, the compiler understands that there is no need to consider those moves .

+49
Jun 23 '15 at 20:44
source share

The main difference is that cloning is explicit. Implicit notation means moving for a non- Copy type.

 // u8 implements Copy let x: u8 = 123; let y = x; // x can still be used println!("x={}, y={}", x, y); // Vec<u8> implements Clone, but not Copy let v: Vec<u8> = vec![1, 2, 3]; let w = v.clone(); //let w = v // This would *move* the value, rendering v unusable. 

By the way, each type of Copy should also be Clone . However, they are not required to do the same! For your own types, .clone() can be an arbitrary method of your choice, while implicit copying always starts the implementation of memcpy , not clone(&self) .

+37
Jun 23 '15 at 20:38
source share



All Articles