Skip to content

Commit bbc8c93

Browse files
committed
Fix inconsistent Clone documentation.
Use function pointer as the example to demonstrate how to implement Clone for Copy types. refs #57123
1 parent 14b9665 commit bbc8c93

File tree

1 file changed

+20
-9
lines changed

1 file changed

+20
-9
lines changed

src/libcore/clone.rs

+20-9
Original file line numberDiff line numberDiff line change
@@ -63,28 +63,39 @@
6363
/// This trait can be used with `#[derive]` if all fields are `Clone`. The `derive`d
6464
/// implementation of [`clone`] calls [`clone`] on each field.
6565
///
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+
///
6677
/// ## How can I implement `Clone`?
6778
///
6879
/// Types that are [`Copy`] should have a trivial implementation of `Clone`. More formally:
6980
/// if `T: Copy`, `x: T`, and `y: &T`, then `let x = y.clone();` is equivalent to `let x = *y;`.
7081
/// Manual implementations should be careful to uphold this invariant; however, unsafe code
7182
/// must not rely on it to ensure memory safety.
7283
///
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:
7686
///
7787
/// [`Copy`]: ../../std/marker/trait.Copy.html
7888
/// [`clone`]: trait.Clone.html#tymethod.clone
7989
///
8090
/// ```
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> {}
8594
///
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+
/// }
8899
/// }
89100
/// ```
90101
///

0 commit comments

Comments
 (0)