Member-only story
Rust: Reassign (with Copy or Clone) vs Mutate
An implementation, memory, and performance comparison between reassignment and mutation in Rust

Knowing when to use mutations versus reassignments is a common decision in many programming languages and in a memory-safe language like Rust, they are an essential question. As Rust is dominated by knowing how to borrow effectively, we can ease our way into its rules by looking at the Rust language through the lens of reassignment versus direct mutation.
Note: After this, read up on Ownership and how it relates to borrowing, slices, and memory management of your Rust variables. You probably already know some of this if you are using Rust, but it does not hurt to read through this section.
In a lot of cases, Rustaceans refer to the performance impact of using something like Clone
or Copy
traits in Rust, which allow duplication of a struct
into a brand-new variable binding.
Below, we will look at the memory impact of using mutable object references, copied objects, and cloned objects alongside code examples (full source code here). Benchmarks at the end.