Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between copied and cloned on Rust iterators

I'm trying to figure out the difference between the copied() and cloned() methods on Rust's Iterator trait. Looking at the docs on Clone, I can see that it...

Differs from Copy in that Copy is implicit and extremely inexpensive, while Clone is always explicit and may or may not be expensive. [...] Since Clone is more general than Copy, you can automatically make anything Copy be Clone as well.

...but for iterators both methods are explicit so what's the point of copied()? Should I just always use cloned() as it will work in the more general case?

like image 773
Zak Avatar asked Oct 16 '19 12:10

Zak


People also ask

What is difference between copy and clone?

clone - create something new based on something that exists. copying - copy from something that exists to something else (that also already exists).

What is a clone in Rust?

A common trait for the ability to explicitly duplicate an object. Differs from Copy in that Copy is implicit and an inexpensive bit-wise copy, while Clone is always explicit and may or may not be expensive.

Are Rust iterators lazy?

In Rust, iterators are lazy, meaning they have no effect until you call methods that consume the iterator to use it up.

How do you copy values in Rust?

You can just use . clone() for your duplicate function.


2 Answers

I managed to find (thanks to Peter!) this pull request which explains the original reasoning behind adding copied() in addition to cloned()...

The intent of copied is to avoid accidentally cloning iterator elements after doing a code refactoring which causes a structure to be no longer Copy. This is a relatively common pattern, as it can be seen by calling rg --pcre2 '[.]map[(][|](?:(\w+)[|] [*]\1|&(\w+)[|] \2)[)]' on Rust main repository. Additionally, many uses of cloned actually want to simply Copy, and changing something to be no longer copyable may introduce unnoticeable performance penalty.

like image 175
Zak Avatar answered Sep 27 '22 23:09

Zak


Should I just always use cloned() as it will work in the more general case?

Often, the Rust optimiser will be able to figure out that a clone can be replaced with a faster copy. However, this isn't guaranteed, so use copied() where you can, to make sure you end up with the fastest binary.

like image 24
Peter Hall Avatar answered Sep 27 '22 23:09

Peter Hall