dyn-clone
A Clone trait that works with trait objects, letting you clone boxed dyn values in Rust.
Repository Health
Technical Analysis
dyn-clone is a Rust library that provides a DynClone trait usable in trait objects, solving the long-standing problem that the standard library’s Clone is not object-safe. With it you can clone a Box<dyn Trait> when your trait extends DynClone, and any type that already implements the standard Clone is automatically usable through a DynClone trait object. A companion macro generates the Clone implementation for the boxed trait object so cloning feels completely natural.
What You Get
- A dyn-compatible
DynClonetrait that can be used as a supertrait of your own traits - A
clone_boxfunction that clones any sized or unsizedDynCloneimplementation into aBox - A
clone_trait_object!macro that generatesClonefor your boxed trait object - Automatic support for any type that already implements the standard library
Clone
Common Use Cases
- Cloning heterogeneous collections of
Box<dyn Trait>values - Duplicating plugin or strategy objects held behind a trait object
- Building cloneable trees or graphs whose nodes are trait objects
Under The Hood
Architecture
dyn-clone is built on a private DynClone trait with a single __clone_box method returning a raw pointer to a freshly allocated clone. A blanket implementation covers every T: Clone, so concrete types get it for free. The public clone_box function reconstitutes the raw pointer into a proper Box, and the clone_trait_object! macro emits an impl Clone for Box<dyn YourTrait> that forwards to clone_box, making the whole mechanism invisible at call sites.
Tech Stack
A minimal pure-Rust crate by David Tolnay with no runtime dependencies, supporting no-std via an optional feature. It targets stable Rust, is dual-licensed Apache-2.0/MIT, and lives in essentially two source files plus tests, reflecting its role as a tiny foundational utility.
Code Quality
The code is small, meticulous, and heavily used across the ecosystem, with three test files including a compiletest suite that pins down expected type-level errors alongside functional trait and macro tests. The unsafe involved in the box reconstruction is narrowly scoped and carefully documented, consistent with the author’s other widely trusted crates.
API Design
The developer experience is excellent for such a subtle capability: extend your trait with DynClone, add one macro invocation, and Box<dyn Trait> becomes cloneable with ordinary .clone() syntax. The README’s worked example makes the pattern obvious, and because it reuses the standard Clone trait there is almost nothing new to learn.