|
63 | 63 | /// This trait can be used with `#[derive]` if all fields are `Clone`. The `derive`d |
64 | 64 | /// implementation of [`clone`] calls [`clone`] on each field. |
65 | 65 | /// |
| 66 | +/// For a generic struct, `#[derive]` implements `Clone` conditionally by adding bound `Clone` on |
| 67 | +/// generic parameters. |
| 68 | +/// |
| 69 | +/// ``` |
| 70 | +/// // `derive` implements Clone for Reading<T> when T is Clone. |
| 71 | +/// #[derive(Clone)] |
| 72 | +/// struct Reading<T> { |
| 73 | +/// frequency: T, |
| 74 | +/// } |
| 75 | +/// ``` |
| 76 | +/// |
66 | 77 | /// ## How can I implement `Clone`? |
67 | 78 | /// |
68 | 79 | /// Types that are [`Copy`] should have a trivial implementation of `Clone`. More formally: |
69 | 80 | /// if `T: Copy`, `x: T`, and `y: &T`, then `let x = y.clone();` is equivalent to `let x = *y;`. |
70 | 81 | /// Manual implementations should be careful to uphold this invariant; however, unsafe code |
71 | 82 | /// must not rely on it to ensure memory safety. |
72 | 83 | /// |
73 | | -/// An example is an array holding more than 32 elements of a type that is `Clone`; the standard |
74 | | -/// library only implements `Clone` up until arrays of size 32. In this case, the implementation of |
75 | | -/// `Clone` cannot be `derive`d, but can be implemented as: |
| 84 | +/// An example is a generic struct holding a function pointer. In this case, the |
| 85 | +/// implementation of `Clone` cannot be `derive`d, but can be implemented as: |
76 | 86 | /// |
77 | 87 | /// [`Copy`]: ../../std/marker/trait.Copy.html |
78 | 88 | /// [`clone`]: trait.Clone.html#tymethod.clone |
79 | 89 | /// |
80 | 90 | /// ``` |
81 | | -/// #[derive(Copy)] |
82 | | -/// struct Stats { |
83 | | -/// frequencies: [i32; 100], |
84 | | -/// } |
| 91 | +/// struct Generate<T>(fn() -> T); |
| 92 | +/// |
| 93 | +/// impl<T> Copy for Generate<T> {} |
85 | 94 | /// |
86 | | -/// impl Clone for Stats { |
87 | | -/// fn clone(&self) -> Stats { *self } |
| 95 | +/// impl<T> Clone for Generate<T> { |
| 96 | +/// fn clone(&self) -> Self { |
| 97 | +/// *self |
| 98 | +/// } |
88 | 99 | /// } |
89 | 100 | /// ``` |
90 | 101 | /// |
|
0 commit comments