Post

HN
Hacker News (Newest)

Tips and tricks to avoid cloning in Rust

In Rust, it is often better to avoid cloning if possible to avoid unnecessary allocation. Here is a list of techniques I use most often to do that. All titles are links to Rust playgrounds if you want to play with the examples.

For small data types, cloning might actually be the cheapest option. There is a special trait for that named Copy .

Whenever possible, you should implement that trait on your data types. It makes the code a lot simpler because you don't have to worry about ownership at all. The borrow checker will let you pass your types implementing Copy around freely, for example:

See the doc to know when you can, should and can't implement Copy for your type.

In practice, the most common usage I have for it is for newtypes and enums:

Oftentimes, a function doesn't need to take ownership of its parameters and is able to work with a reference, for example: