Skip to main content

DeepClone

Derive Macro DeepClone 

Source
#[derive(DeepClone)]
{
    // Attributes available to this derive:
    #[deepclone]
}
Expand description

Derive DeepClone, cloning every field through the same Cloner.

Structs (named, tuple, and unit), enums, generics, and where-clauses are supported. Unions are not, unless #[deepclone(clone)] makes the fields irrelevant. Every type parameter gains a DeepClone bound, as derive(Clone) adds a Clone bound.

Nothing here inspects field types: Rc and Arc reach the cloner through their own DeepClone impls, so Vec<Rc<T>> and HashMap<K, Rc<T>> work too, which a derive matching on the literal token Rc would miss.

No 'static bound is added, so a generic type with an Rc<..T..> field needs T: 'static on its own declaration.

§Field attributes

  • #[deepclone(clone)] — use Clone::clone, which on an Rc shares the allocation. Preferrable (and correct) when nothing reachable through the field can be mutated.
  • #[deepclone(with = path)] — call path(&field, cloner).
  • #[deepclone(default)] — ignore the source value and use Default::default().

§Container attributes

  • #[deepclone(clone)] — clone the whole value with Clone::clone instead of field by field. The right answer for a type that reaches nothing shared, since it asks nothing of the field types, so they need no DeepClone impl of their own. Bounds each type parameter by Clone rather than DeepClone.
  • #[deepclone(bound = "T: MyBound")] — replace the generated bounds, for when a DeepClone bound on every parameter is too strong.