core/
clone.rs

1//! The `Clone` trait for types that cannot be 'implicitly copied'. 2//! 3//! In Rust, some simple types are "implicitly copyable" and when you 4//! assign them or pass them as arguments, the receiver will get a copy, 5//! leaving the original value in place. These types do not require 6//! allocation to copy and do not have finalizers (i.e., they do not 7//! contain owned boxes or implement [`Drop`]), so the compiler considers 8//! them cheap and safe to copy. For other types copies must be made 9//! explicitly, by convention implementing the [`Clone`] trait and calling 10//! the [`clone`] method. 11//! 12//! [`clone`]: Clone::clone 13//! 14//! Basic usage example: 15//! 16//! ``` 17//! let s = String::new(); // String type implements Clone 18//! let copy = s.clone(); // so we can clone it 19//! ``` 20//! 21//! To easily implement the Clone trait, you can also use 22//! `#[derive(Clone)]`. Example: 23//! 24//! ``` 25//! #[derive(Clone)] // we add the Clone trait to Morpheus struct 26//! struct Morpheus { 27//!    blue_pill: f32, 28//!    red_pill: i64, 29//! } 30//! 31//! fn main() { 32//!    let f = Morpheus { blue_pill: 0.0, red_pill: 0 }; 33//!    let copy = f.clone(); // and now we can clone it! 34//! } 35//! ``` 36 37#![stable(feature = "rust1", since = "1.0.0")] 38 39use crate::marker::{Destruct, PointeeSized}; 40 41mod uninit; 42 43/// A common trait that allows explicit creation of a duplicate value. 44/// 45/// Calling [`clone`] always produces a new value. 46/// However, for types that are references to other data (such as smart pointers or references), 47/// the new value may still point to the same underlying data, rather than duplicating it. 48/// See [`Clone::clone`] for more details. 49/// 50/// This distinction is especially important when using `#[derive(Clone)]` on structs containing 51/// smart pointers like `Arc<Mutex<T>>` - the cloned struct will share mutable state with the 52/// original. 53/// 54/// Differs from [`Copy`] in that [`Copy`] is implicit and an inexpensive bit-wise copy, while 55/// `Clone` is always explicit and may or may not be expensive. In order to enforce 56/// these characteristics, Rust does not allow you to reimplement [`Copy`], but you 57/// may reimplement `Clone` and run arbitrary code. 58/// 59/// Since `Clone` is more general than [`Copy`], you can automatically make anything 60/// [`Copy`] be `Clone` as well. 61/// 62/// ## Derivable 63/// 64/// This trait can be used with `#[derive]` if all fields are `Clone`. The `derive`d 65/// implementation of [`Clone`] calls [`clone`] on each field. 66/// 67/// [`clone`]: Clone::clone 68/// 69/// For a generic struct, `#[derive]` implements `Clone` conditionally by adding bound `Clone` on 70/// generic parameters. 71/// 72/// ``` 73/// // `derive` implements Clone for Reading<T> when T is Clone. 74/// #[derive(Clone)] 75/// struct Reading<T> { 76///     frequency: T, 77/// } 78/// ``` 79/// 80/// ## How can I implement `Clone`? 81/// 82/// Types that are [`Copy`] should have a trivial implementation of `Clone`. More formally: 83/// if `T: Copy`, `x: T`, and `y: &T`, then `let x = y.clone();` is equivalent to `let x = *y;`. 84/// Manual implementations should be careful to uphold this invariant; however, unsafe code 85/// must not rely on it to ensure memory safety. 86/// 87/// An example is a generic struct holding a function pointer. In this case, the 88/// implementation of `Clone` cannot be `derive`d, but can be implemented as: 89/// 90/// ``` 91/// struct Generate<T>(fn() -> T); 92/// 93/// impl<T> Copy for Generate<T> {} 94/// 95/// impl<T> Clone for Generate<T> { 96///     fn clone(&self) -> Self { 97///         *self 98///     } 99/// } 100/// ``` 101/// 102/// If we `derive`: 103/// 104/// ``` 105/// #[derive(Copy, Clone)] 106/// struct Generate<T>(fn() -> T); 107/// ``` 108/// 109/// the auto-derived implementations will have unnecessary `T: Copy` and `T: Clone` bounds: 110/// 111/// ``` 112/// # struct Generate<T>(fn() -> T); 113/// 114/// // Automatically derived 115/// impl<T: Copy> Copy for Generate<T> { } 116/// 117/// // Automatically derived 118/// impl<T: Clone> Clone for Generate<T> { 119///     fn clone(&self) -> Generate<T> { 120///         Generate(Clone::clone(&self.0)) 121///     } 122/// } 123/// ``` 124/// 125/// The bounds are unnecessary because clearly the function itself should be 126/// copy- and cloneable even if its return type is not: 127/// 128/// ```compile_fail,E0599 129/// #[derive(Copy, Clone)] 130/// struct Generate<T>(fn() -> T); 131/// 132/// struct NotCloneable; 133/// 134/// fn generate_not_cloneable() -> NotCloneable { 135///     NotCloneable 136/// } 137/// 138/// Generate(generate_not_cloneable).clone(); // error: trait bounds were not satisfied 139/// // Note: With the manual implementations the above line will compile. 140/// ``` 141/// 142/// ## `Clone` and `PartialEq`/`Eq` 143/// `Clone` is intended for the duplication of objects. Consequently, when implementing 144/// both `Clone` and [`PartialEq`], the following property is expected to hold: 145/// ```text 146/// x == x -> x.clone() == x 147/// ``` 148/// In other words, if an object compares equal to itself, 149/// its clone must also compare equal to the original. 150/// 151/// For types that also implement [`Eq`] – for which `x == x` always holds – 152/// this implies that `x.clone() == x` must always be true. 153/// Standard library collections such as 154/// [`HashMap`], [`HashSet`], [`BTreeMap`], [`BTreeSet`] and [`BinaryHeap`] 155/// rely on their keys respecting this property for correct behavior. 156/// Furthermore, these collections require that cloning a key preserves the outcome of the 157/// [`Hash`] and [`Ord`] methods. Thankfully, this follows automatically from `x.clone() == x` 158/// if `Hash` and `Ord` are correctly implemented according to their own requirements. 159/// 160/// When deriving both `Clone` and [`PartialEq`] using `#[derive(Clone, PartialEq)]` 161/// or when additionally deriving [`Eq`] using `#[derive(Clone, PartialEq, Eq)]`, 162/// then this property is automatically upheld – provided that it is satisfied by 163/// the underlying types. 164/// 165/// Violating this property is a logic error. The behavior resulting from a logic error is not 166/// specified, but users of the trait must ensure that such logic errors do *not* result in 167/// undefined behavior. This means that `unsafe` code **must not** rely on this property 168/// being satisfied. 169/// 170/// ## Additional implementors 171/// 172/// In addition to the [implementors listed below][impls], 173/// the following types also implement `Clone`: 174/// 175/// * Function item types (i.e., the distinct types defined for each function) 176/// * Function pointer types (e.g., `fn() -> i32`) 177/// * Closure types, if they capture no value from the environment 178///   or if all such captured values implement `Clone` themselves. 179///   Note that variables captured by shared reference always implement `Clone` 180///   (even if the referent doesn't), 181///   while variables captured by mutable reference never implement `Clone`. 182/// 183/// [`HashMap`]: ../../std/collections/struct.HashMap.html 184/// [`HashSet`]: ../../std/collections/struct.HashSet.html 185/// [`BTreeMap`]: ../../std/collections/struct.BTreeMap.html 186/// [`BTreeSet`]: ../../std/collections/struct.BTreeSet.html 187/// [`BinaryHeap`]: ../../std/collections/struct.BinaryHeap.html 188/// [impls]: #implementors 189#[stable(feature = "rust1", since = "1.0.0")] 190#[lang = "clone"] 191#[rustc_diagnostic_item = "Clone"] 192#[rustc_trivial_field_reads] 193#[rustc_const_unstable(feature = "const_clone", issue = "142757")] 194#[const_trait] 195pub trait Clone: Sized { 196    /// Returns a duplicate of the value. 197    /// 198    /// Note that what "duplicate" means varies by type: 199    /// - For most types, this creates a deep, independent copy 200    /// - For reference types like `&T`, this creates another reference to the same value 201    /// - For smart pointers like [`Arc`] or [`Rc`], this increments the reference count 202    ///   but still points to the same underlying data 203    /// 204    /// [`Arc`]: ../../std/sync/struct.Arc.html 205    /// [`Rc`]: ../../std/rc/struct.Rc.html 206    /// 207    /// # Examples 208    /// 209    /// ``` 210    /// # #![allow(noop_method_call)] 211    /// let hello = "Hello"; // &str implements Clone 212    /// 213    /// assert_eq!("Hello", hello.clone()); 214    /// ``` 215    /// 216    /// Example with a reference-counted type: 217    /// 218    /// ``` 219    /// use std::sync::{Arc, Mutex}; 220    /// 221    /// let data = Arc::new(Mutex::new(vec![1, 2, 3])); 222    /// let data_clone = data.clone(); // Creates another Arc pointing to the same Mutex 223    /// 224    /// { 225    ///     let mut lock = data.lock().unwrap(); 226    ///     lock.push(4); 227    /// } 228    /// 229    /// // Changes are visible through the clone because they share the same underlying data 230    /// assert_eq!(*data_clone.lock().unwrap(), vec![1, 2, 3, 4]); 231    /// ``` 232    #[stable(feature = "rust1", since = "1.0.0")] 233    #[must_use = "cloning is often expensive and is not expected to have side effects"] 234    // Clone::clone is special because the compiler generates MIR to implement it for some types. 235    // See InstanceKind::CloneShim. 236    #[lang = "clone_fn"] 237    fn clone(&self) -> Self; 238 239    /// Performs copy-assignment from `source`. 240    /// 241    /// `a.clone_from(&b)` is equivalent to `a = b.clone()` in functionality, 242    /// but can be overridden to reuse the resources of `a` to avoid unnecessary 243    /// allocations. 244    #[inline] 245    #[stable(feature = "rust1", since = "1.0.0")] 246    fn clone_from(&mut self, source: &Self) 247    where 248        Self: [const] Destruct, 249    { 250        *self = source.clone() 251    } 252} 253 254/// Derive macro generating an impl of the trait `Clone`. 255#[rustc_builtin_macro] 256#[stable(feature = "builtin_macro_prelude", since = "1.38.0")] 257#[allow_internal_unstable(core_intrinsics, derive_clone_copy)] 258pub macro Clone($item:item) { 259    /* compiler built-in */ 260} 261 262/// Trait for objects whose [`Clone`] impl is lightweight (e.g. reference-counted) 263/// 264/// Cloning an object implementing this trait should in general: 265/// - be O(1) (constant) time regardless of the amount of data managed by the object, 266/// - not require a memory allocation, 267/// - not require copying more than roughly 64 bytes (a typical cache line size), 268/// - not block the current thread, 269/// - not have any semantic side effects (e.g. allocating a file descriptor), and 270/// - not have overhead larger than a couple of atomic operations. 271/// 272/// The `UseCloned` trait does not provide a method; instead, it indicates that 273/// `Clone::clone` is lightweight, and allows the use of the `.use` syntax. 274/// 275/// ## .use postfix syntax 276/// 277/// Values can be `.use`d by adding `.use` postfix to the value you want to use. 278/// 279/// ```ignore (this won't work until we land use) 280/// fn foo(f: Foo) { 281///     // if `Foo` implements `Copy` f would be copied into x. 282///     // if `Foo` implements `UseCloned` f would be cloned into x. 283///     // otherwise f would be moved into x. 284///     let x = f.use; 285///     // ... 286/// } 287/// ``` 288/// 289/// ## use closures 290/// 291/// Use closures allow captured values to be automatically used. 292/// This is similar to have a closure that you would call `.use` over each captured value. 293#[unstable(feature = "ergonomic_clones", issue = "132290")] 294#[lang = "use_cloned"] 295pub trait UseCloned: Clone { 296    // Empty. 297} 298 299macro_rules! impl_use_cloned { 300    ($($t:ty)*) => { 301        $( 302            #[unstable(feature = "ergonomic_clones", issue = "132290")] 303            impl UseCloned for $t {} 304        )* 305    } 306} 307 308impl_use_cloned! { 309    usize u8 u16 u32 u64 u128 310    isize i8 i16 i32 i64 i128 311             f16 f32 f64 f128 312    bool char 313} 314 315// FIXME(aburka): these structs are used solely by #[derive] to 316// assert that every component of a type implements Clone or Copy. 317// 318// These structs should never appear in user code. 319#[doc(hidden)] 320#[allow(missing_debug_implementations)] 321#[unstable( 322    feature = "derive_clone_copy", 323    reason = "deriving hack, should not be public", 324    issue = "none" 325)] 326pub struct AssertParamIsClone<T: Clone + PointeeSized> { 327    _field: crate::marker::PhantomData<T>, 328} 329#[doc(hidden)] 330#[allow(missing_debug_implementations)] 331#[unstable( 332    feature = "derive_clone_copy", 333    reason = "deriving hack, should not be public", 334    issue = "none" 335)] 336pub struct AssertParamIsCopy<T: Copy + PointeeSized> { 337    _field: crate::marker::PhantomData<T>, 338} 339 340/// A generalization of [`Clone`] to [dynamically-sized types][DST] stored in arbitrary containers. 341/// 342/// This trait is implemented for all types implementing [`Clone`], [slices](slice) of all 343/// such types, and other dynamically-sized types in the standard library. 344/// You may also implement this trait to enable cloning custom DSTs 345/// (structures containing dynamically-sized fields), or use it as a supertrait to enable 346/// cloning a [trait object]. 347/// 348/// This trait is normally used via operations on container types which support DSTs, 349/// so you should not typically need to call `.clone_to_uninit()` explicitly except when 350/// implementing such a container or otherwise performing explicit management of an allocation, 351/// or when implementing `CloneToUninit` itself. 352/// 353/// # Safety 354/// 355/// Implementations must ensure that when `.clone_to_uninit(dest)` returns normally rather than 356/// panicking, it always leaves `*dest` initialized as a valid value of type `Self`. 357/// 358/// # Examples 359/// 360// FIXME(#126799): when `Box::clone` allows use of `CloneToUninit`, rewrite these examples with it 361// since `Rc` is a distraction. 362/// 363/// If you are defining a trait, you can add `CloneToUninit` as a supertrait to enable cloning of 364/// `dyn` values of your trait: 365/// 366/// ``` 367/// #![feature(clone_to_uninit)] 368/// use std::rc::Rc; 369/// 370/// trait Foo: std::fmt::Debug + std::clone::CloneToUninit { 371///     fn modify(&mut self); 372///     fn value(&self) -> i32; 373/// } 374/// 375/// impl Foo for i32 { 376///     fn modify(&mut self) { 377///         *self *= 10; 378///     } 379///     fn value(&self) -> i32 { 380///         *self 381///     } 382/// } 383/// 384/// let first: Rc<dyn Foo> = Rc::new(1234); 385/// 386/// let mut second = first.clone(); 387/// Rc::make_mut(&mut second).modify(); // make_mut() will call clone_to_uninit() 388/// 389/// assert_eq!(first.value(), 1234); 390/// assert_eq!(second.value(), 12340); 391/// ``` 392/// 393/// The following is an example of implementing `CloneToUninit` for a custom DST. 394/// (It is essentially a limited form of what `derive(CloneToUninit)` would do, 395/// if such a derive macro existed.) 396/// 397/// ``` 398/// #![feature(clone_to_uninit)] 399/// use std::clone::CloneToUninit; 400/// use std::mem::offset_of; 401/// use std::rc::Rc; 402/// 403/// #[derive(PartialEq)] 404/// struct MyDst<T: ?Sized> { 405///     label: String, 406///     contents: T, 407/// } 408/// 409/// unsafe impl<T: ?Sized + CloneToUninit> CloneToUninit for MyDst<T> { 410///     unsafe fn clone_to_uninit(&self, dest: *mut u8) { 411///         // The offset of `self.contents` is dynamic because it depends on the alignment of T 412///         // which can be dynamic (if `T = dyn SomeTrait`). Therefore, we have to obtain it 413///         // dynamically by examining `self`, rather than using `offset_of!`. 414///         // 415///         // SAFETY: `self` by definition points somewhere before `&self.contents` in the same 416///         // allocation. 417///         let offset_of_contents = unsafe { 418///             (&raw const self.contents).byte_offset_from_unsigned(self) 419///         }; 420/// 421///         // Clone the *sized* fields of `self` (just one, in this example). 422///         // (By cloning this first and storing it temporarily in a local variable, we avoid 423///         // leaking it in case of any panic, using the ordinary automatic cleanup of local 424///         // variables. Such a leak would be sound, but undesirable.) 425///         let label = self.label.clone(); 426/// 427///         // SAFETY: The caller must provide a `dest` such that these field offsets are valid 428///         // to write to. 429///         unsafe { 430///             // Clone the unsized field directly from `self` to `dest`. 431///             self.contents.clone_to_uninit(dest.add(offset_of_contents)); 432/// 433///             // Now write all the sized fields. 434///             // 435///             // Note that we only do this once all of the clone() and clone_to_uninit() calls 436///             // have completed, and therefore we know that there are no more possible panics; 437///             // this ensures no memory leaks in case of panic. 438///             dest.add(offset_of!(Self, label)).cast::<String>().write(label); 439///         } 440///         // All fields of the struct have been initialized; therefore, the struct is initialized, 441///         // and we have satisfied our `unsafe impl CloneToUninit` obligations. 442///     } 443/// } 444/// 445/// fn main() { 446///     // Construct MyDst<[u8; 4]>, then coerce to MyDst<[u8]>. 447///     let first: Rc<MyDst<[u8]>> = Rc::new(MyDst { 448///         label: String::from("hello"), 449///         contents: [1, 2, 3, 4], 450///     }); 451/// 452///     let mut second = first.clone(); 453///     // make_mut() will call clone_to_uninit(). 454///     for elem in Rc::make_mut(&mut second).contents.iter_mut() { 455///         *elem *= 10; 456///     } 457/// 458///     assert_eq!(first.contents, [1, 2, 3, 4]); 459///     assert_eq!(second.contents, [10, 20, 30, 40]); 460///     assert_eq!(second.label, "hello"); 461/// } 462/// ``` 463/// 464/// # See Also 465/// 466/// * [`Clone::clone_from`] is a safe function which may be used instead when [`Self: Sized`](Sized) 467///   and the destination is already initialized; it may be able to reuse allocations owned by 468///   the destination, whereas `clone_to_uninit` cannot, since its destination is assumed to be 469///   uninitialized. 470/// * [`ToOwned`], which allocates a new destination container. 471/// 472/// [`ToOwned`]: ../../std/borrow/trait.ToOwned.html 473/// [DST]: https://doc.rust-lang.org/reference/dynamically-sized-types.html 474/// [trait object]: https://doc.rust-lang.org/reference/types/trait-object.html 475#[unstable(feature = "clone_to_uninit", issue = "126799")] 476pub unsafe trait CloneToUninit { 477    /// Performs copy-assignment from `self` to `dest`. 478    /// 479    /// This is analogous to `std::ptr::write(dest.cast(), self.clone())`, 480    /// except that `Self` may be a dynamically-sized type ([`!Sized`](Sized)). 481    /// 482    /// Before this function is called, `dest` may point to uninitialized memory. 483    /// After this function is called, `dest` will point to initialized memory; it will be 484    /// sound to create a `&Self` reference from the pointer with the [pointer metadata] 485    /// from `self`. 486    /// 487    /// # Safety 488    /// 489    /// Behavior is undefined if any of the following conditions are violated: 490    /// 491    /// * `dest` must be [valid] for writes for `size_of_val(self)` bytes. 492    /// * `dest` must be properly aligned to `align_of_val(self)`. 493    /// 494    /// [valid]: crate::ptr#safety 495    /// [pointer metadata]: crate::ptr::metadata() 496    /// 497    /// # Panics 498    /// 499    /// This function may panic. (For example, it might panic if memory allocation for a clone 500    /// of a value owned by `self` fails.) 501    /// If the call panics, then `*dest` should be treated as uninitialized memory; it must not be 502    /// read or dropped, because even if it was previously valid, it may have been partially 503    /// overwritten. 504    /// 505    /// The caller may wish to take care to deallocate the allocation pointed to by `dest`, 506    /// if applicable, to avoid a memory leak (but this is not a requirement). 507    /// 508    /// Implementors should avoid leaking values by, upon unwinding, dropping all component values 509    /// that might have already been created. (For example, if a `[Foo]` of length 3 is being 510    /// cloned, and the second of the three calls to `Foo::clone()` unwinds, then the first `Foo` 511    /// cloned should be dropped.) 512    unsafe fn clone_to_uninit(&self, dest: *mut u8); 513} 514 515#[unstable(feature = "clone_to_uninit", issue = "126799")] 516unsafe impl<T: Clone> CloneToUninit for T { 517    #[inline] 518    unsafe fn clone_to_uninit(&self, dest: *mut u8) { 519        // SAFETY: we're calling a specialization with the same contract 520        unsafe { <T as self::uninit::CopySpec>::clone_one(self, dest.cast::<T>()) } 521    } 522} 523 524#[unstable(feature = "clone_to_uninit", issue = "126799")] 525unsafe impl<T: Clone> CloneToUninit for [T] { 526    #[inline] 527    #[cfg_attr(debug_assertions, track_caller)] 528    unsafe fn clone_to_uninit(&self, dest: *mut u8) { 529        let dest: *mut [T] = dest.with_metadata_of(self); 530        // SAFETY: we're calling a specialization with the same contract 531        unsafe { <T as self::uninit::CopySpec>::clone_slice(self, dest) } 532    } 533} 534 535#[unstable(feature = "clone_to_uninit", issue = "126799")] 536unsafe impl CloneToUninit for str { 537    #[inline] 538    #[cfg_attr(debug_assertions, track_caller)] 539    unsafe fn clone_to_uninit(&self, dest: *mut u8) { 540        // SAFETY: str is just a [u8] with UTF-8 invariant 541        unsafe { self.as_bytes().clone_to_uninit(dest) } 542    } 543} 544 545#[unstable(feature = "clone_to_uninit", issue = "126799")] 546unsafe impl CloneToUninit for crate::ffi::CStr { 547    #[cfg_attr(debug_assertions, track_caller)] 548    unsafe fn clone_to_uninit(&self, dest: *mut u8) { 549        // SAFETY: For now, CStr is just a #[repr(trasnsparent)] [c_char] with some invariants. 550        // And we can cast [c_char] to [u8] on all supported platforms (see: to_bytes_with_nul). 551        // The pointer metadata properly preserves the length (so NUL is also copied). 552        // See: `cstr_metadata_is_length_with_nul` in tests. 553        unsafe { self.to_bytes_with_nul().clone_to_uninit(dest) } 554    } 555} 556 557#[unstable(feature = "bstr", issue = "134915")] 558unsafe impl CloneToUninit for crate::bstr::ByteStr { 559    #[inline] 560    #[cfg_attr(debug_assertions, track_caller)] 561    unsafe fn clone_to_uninit(&self, dst: *mut u8) { 562        // SAFETY: ByteStr is a `#[repr(transparent)]` wrapper around `[u8]` 563        unsafe { self.as_bytes().clone_to_uninit(dst) } 564    } 565} 566 567/// Implementations of `Clone` for primitive types. 568/// 569/// Implementations that cannot be described in Rust 570/// are implemented in `traits::SelectionContext::copy_clone_conditions()` 571/// in `rustc_trait_selection`. 572mod impls { 573    use crate::marker::PointeeSized; 574 575    macro_rules! impl_clone { 576        ($($t:ty)*) => { 577            $( 578                #[stable(feature = "rust1", since = "1.0.0")] 579                impl Clone for $t { 580                    #[inline(always)] 581                    fn clone(&self) -> Self { 582                        *self 583                    } 584                } 585            )* 586        } 587    } 588 589    impl_clone! { 590        usize u8 u16 u32 u64 u128 591        isize i8 i16 i32 i64 i128 592        f16 f32 f64 f128 593        bool char 594    } 595 596    #[unstable(feature = "never_type", issue = "35121")] 597    impl Clone for ! { 598        #[inline] 599        fn clone(&self) -> Self { 600            *self 601        } 602    } 603 604    #[stable(feature = "rust1", since = "1.0.0")] 605    impl<T: PointeeSized> Clone for *const T { 606        #[inline(always)] 607        fn clone(&self) -> Self { 608            *self 609        } 610    } 611 612    #[stable(feature = "rust1", since = "1.0.0")] 613    impl<T: PointeeSized> Clone for *mut T { 614        #[inline(always)] 615        fn clone(&self) -> Self { 616            *self 617        } 618    } 619 620    /// Shared references can be cloned, but mutable references *cannot*! 621    #[stable(feature = "rust1", since = "1.0.0")] 622    impl<T: PointeeSized> Clone for &T { 623        #[inline(always)] 624        #[rustc_diagnostic_item = "noop_method_clone"] 625        fn clone(&self) -> Self { 626            self 627        } 628    } 629 630    /// Shared references can be cloned, but mutable references *cannot*! 631    #[stable(feature = "rust1", since = "1.0.0")] 632    impl<T: PointeeSized> !Clone for &mut T {} 633}