Rust-specific Patterns
Recipe | Crates | Categories |
---|---|---|
Clone a Struct Storing a Boxed Trait Object | ||
pin-project and pin-project-lite |
FIXME
Clone a Struct Storing a Boxed Trait Object
The dyn-clone
⮳ crate provides a DynClone
trait that can be used in trait objects, and a clone_box
⮳ function that can clone any sized or dynamically sized implementation of DynClone
. Types that implement the standard library's std::clone::Clone
⮳ trait are automatically usable by a DynClone
trait object.
//! Demonstrates how to clone trait objects using the `dyn_clone` crate. use dyn_clone::DynClone; // Define a trait named `MyTrait` that requires implementors to also implement // `DynClone`. trait MyTrait: DynClone { fn recite(&self); } // Implement `MyTrait` for `String``. impl MyTrait for String { fn recite(&self) { println!("{} ♫", self); } } fn main() { let line = "The slithy structs did gyre and gimble the namespace"; // Build a trait object holding a String. // This requires `String` to implement `MyTrait`. let original_trait_object: Box<dyn MyTrait> = Box::new(String::from(line)); // Call the `MyTrait` function. original_trait_object.recite(); // Clone the trait object. let cloned_trait_object: Box<dyn MyTrait> = dyn_clone::clone_box(&*original_trait_object); // Call the `MyTrait` function on the cloned object. cloned_trait_object.recite(); }
pin-project
and pin-project-lite
pin-project
⮳ is a crate for safe and ergonomic pin-projection. The #[pin_project]
attribute creates projection types covering all the fields of struct or enum.
pin-project-lite
is a lightweight version of pin-project
written with declarative macros. The pin_project!
macro creates a projection type covering all the fields of struct.
// // COMING SOON
See also: