|
46 | 46 |
|
47 | 47 | use marker::Sized;
|
48 | 48 |
|
49 |
| -/// A common trait for cloning an object. |
| 49 | +/// A common trait for cloning an object. Differs from `Copy` in that you can |
| 50 | +/// define `Clone` to run arbitrary code, while you are not allowed to override |
| 51 | +/// the implementation of `Copy` that only does a `memcpy`. |
| 52 | +/// |
| 53 | +/// Since `Clone` is more general than `Copy`, you can automatically make anything |
| 54 | +/// `Copy` be `Clone` as well. |
| 55 | +/// |
| 56 | +/// ## Derivable |
50 | 57 | ///
|
51 | 58 | /// This trait can be used with `#[derive]` if all fields are `Clone`. The `derive`d
|
52 | 59 | /// implementation of `clone()` calls `clone()` on each field.
|
53 | 60 | ///
|
| 61 | +/// ## How can I implement `Clone`? |
| 62 | +/// |
54 | 63 | /// Types that are `Copy` should have a trivial implementation of `Clone`. More formally:
|
55 | 64 | /// if `T: Copy`, `x: T`, and `y: &T`, then `let x = y.clone();` is equivalent to `let x = *y;`.
|
56 | 65 | /// Manual implementations should be careful to uphold this invariant; however, unsafe code
|
57 | 66 | /// must not rely on it to ensure memory safety.
|
| 67 | +/// |
| 68 | +/// An example is an array holding more than 32 of a type that is `Clone`; the standard library |
| 69 | +/// only implements `Clone` up until arrays of size 32. In this case, the implementation of |
| 70 | +/// `Clone` cannot be `derive`d, but can be implemented as: |
| 71 | +/// |
| 72 | +/// ``` |
| 73 | +/// #[derive(Copy)] |
| 74 | +/// struct Stats { |
| 75 | +/// frequencies: [i32; 100], |
| 76 | +/// } |
| 77 | +/// |
| 78 | +/// impl Clone for Stats { |
| 79 | +/// fn clone(&self) -> Self { *self } |
| 80 | +/// } |
| 81 | +/// ``` |
58 | 82 | #[stable(feature = "rust1", since = "1.0.0")]
|
59 | 83 | pub trait Clone : Sized {
|
60 | 84 | /// Returns a copy of the value.
|
|
0 commit comments