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