-
Book Overview & Buying
-
Table Of Contents
Design Patterns and Best Practices in Rust
By :
In this section, we'll explore the Prototype pattern and its relationship with Rust's built-in traits. While Prototype is traditionally used to clone objects in object-oriented languages, Rust's Clone and Default traits often provide better alternatives. We'll see how these traits give us the benefits of the Prototype pattern while maintaining Rust's safety and clarity.
The Prototype pattern traditionally allows creating new objects by cloning existing ones. In our calculator, we might want to create new expressions based on existing ones while sharing common subexpressions. We could also provide template expressions for common calculations.
Let's see how Rust's traits help us achieve the Prototype pattern's goals. The first step is making our Expression type cloneable, which #[derive(Clone)] handles automatically. This alone gives us basic prototype functionality. Any expression can serve as a template for new expressions...