Rust: Clone vs Copy

One of the strength of Rust is memory management. This also leads to compiler errors related to move or borrow When we assign an existing variable to new variable, two things can happen.

Either the data is copied - in that case we can use both old and the new variable without worry. 1

Or data is moved - now we can only use the new variable, as the old variable is “out of scope”. But there is a way to access both the new and old variables. But in that case we have to explicit.

We need to copy the variable.

You may be familiar with concept of shallow copy Vs deep copy. clone in rust is same as deep copy. Here the entire data (String or struct) is copied rather than just the pointer.

Off course, cloning or deep copy means additional memory usage. If the data is huge, then be careful with cloning.

You can read detailed description about the memory management in the rust book 2


  1. Scalar data types like number and characters are copied by default ↩︎

  2. Memory management in Rust ↩︎