Member-only story

Rust: Reassign (with Copy or Clone) vs Mutate

Cameron Manavian
Level Up Coding
Published in
6 min readAug 27, 2020

An implementation, memory, and performance comparison between reassignment and mutation in Rust

Image credit: The Product Analyst

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.

Simple Example: Bicycle — Clone vs Mutate

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Responses (2)

Write a response

[[bin]]
name = "clone_bikes"
path = "src/clone_bikes.rs"

If you put all of your binary entry points into `src/bin/` instead of `src/` they would be detected automatically, without listing them here.

I suggest you check assembler output, these definitely seem like a case where the copy/clone would be optimized away, so your result is very surprising.
Curious if any of the unused fields also made it into the binary.