Tech News
← Back to articles

# [derive(Clone)] Is Broken

read original related products more articles

use std::sync::Arc; struct NoClone ; struct WrapArc (Arc); fn main () { let foo = WrapArc (Arc:: new (NoClone)); let foo_ = foo. clone (); }

Do you think this code should compile?

What about the following code:

struct AlwaysEq (T); impl PartialEq for AlwaysEq { fn eq (& self , _other: & Self ) -> bool { true } } impl Eq for AlwaysEq {} struct NotEq ; struct WrapAlwaysEq (AlwaysEq); fn assert_is_eq (_: impl Eq ) {} fn main () { let x = WrapAlwaysEq ( AlwaysEq (NotEq)); assert_is_eq (x); }

The second example is a bit far fetched, but you probably answered yes.

But neither do.

Why not?

The implementation of #[derive(Clone)] in the Rust compiler generates a Clone implementation with the following requirements on the derived type:

All fields must be Clone .

. All generic parameters must be Clone .

... continue reading