Skip to content
Tech News
← Back to articles

# [derive(Clone)] Is Broken

read original get art supplies → more articles

use std::sync::Arc; struct NoClone ; struct WrapArc <T>(Arc<T>); 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>(T); impl <T> PartialEq for AlwaysEq <T> { fn eq (& self , _other: & Self ) -> bool { true } } impl <T> Eq for AlwaysEq <T> {} struct NotEq ; struct WrapAlwaysEq <T>(AlwaysEq<T>); 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