38
38
39
39
mod uninit;
40
40
41
- /// A common trait for the ability to explicitly duplicate an object.
41
+ /// A common trait that allows explicit creation of a duplicate value.
42
+ ///
43
+ /// Calling [`clone`] always produces a new value.
44
+ /// However, for types that are references to other data (such as smart pointers or references),
45
+ /// the new value may still point to the same underlying data, rather than duplicating it.
46
+ /// See [`Clone::clone`] for more details.
47
+ ///
48
+ /// This distinction is especially important when using `#[derive(Clone)]` on structs containing
49
+ /// smart pointers like `Arc<Mutex<T>>` - the cloned struct will share mutable state with the
50
+ /// original.
42
51
///
43
52
/// Differs from [`Copy`] in that [`Copy`] is implicit and an inexpensive bit-wise copy, while
44
53
/// `Clone` is always explicit and may or may not be expensive. In order to enforce
@@ -147,7 +156,16 @@ mod uninit;
147
156
#[ rustc_diagnostic_item = "Clone" ]
148
157
#[ rustc_trivial_field_reads]
149
158
pub trait Clone : Sized {
150
- /// Returns a copy of the value.
159
+ /// Returns a duplicate of the value.
160
+ ///
161
+ /// Note that what "duplicate" means varies by type:
162
+ /// - For most types, this creates a deep, independent copy
163
+ /// - For reference types like `&T`, this creates another reference to the same value
164
+ /// - For smart pointers like [`Arc`] or [`Rc`], this increments the reference count
165
+ /// but still points to the same underlying data
166
+ ///
167
+ /// [`Arc`]: ../../std/sync/struct.Arc.html
168
+ /// [`Rc`]: ../../std/rc/struct.Rc.html
151
169
///
152
170
/// # Examples
153
171
///
@@ -157,6 +175,23 @@ pub trait Clone: Sized {
157
175
///
158
176
/// assert_eq!("Hello", hello.clone());
159
177
/// ```
178
+ ///
179
+ /// Example with a reference-counted type:
180
+ ///
181
+ /// ```
182
+ /// use std::sync::{Arc, Mutex};
183
+ ///
184
+ /// let data = Arc::new(Mutex::new(vec![1, 2, 3]));
185
+ /// let data_clone = data.clone(); // Creates another Arc pointing to the same Mutex
186
+ ///
187
+ /// {
188
+ /// let mut lock = data.lock().unwrap();
189
+ /// lock.push(4);
190
+ /// }
191
+ ///
192
+ /// // Changes are visible through the clone because they share the same underlying data
193
+ /// assert_eq!(*data_clone.lock().unwrap(), vec![1, 2, 3, 4]);
194
+ /// ```
160
195
#[ stable( feature = "rust1" , since = "1.0.0" ) ]
161
196
#[ must_use = "cloning is often expensive and is not expected to have side effects" ]
162
197
// Clone::clone is special because the compiler generates MIR to implement it for some types.
0 commit comments