-
Book Overview & Buying
-
Table Of Contents
Design Patterns and Best Practices in Rust
By :
In this section, we will explore another common anti-pattern: using clone() whenever there is an error or issue with ownership. Cloning in Rust creates a complete, independent copy of data. The Clone trait provides a clone() method that duplicates a value, allocating new memory and copying all contents. While cloning is exactly the tool to use in some situations, overusing it leads to inefficient code and can mask deeper design issues.
When developers first encounter borrow checker errors, one of the most tempting solutions is to simply clone any data that causes conflicts. This is extremely common, to the extent that almost everyone (including me) did this at the start of their Rust journey. It is an easy way to make the compiler stop complaining, one that does not require careful thinking or refactoring, and it seems to work. Often, it does work to an extent.
There is an old expression, "When what you have is a hammer, everything...