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?
clone - create something new based on something that exists. copying - copy from something that exists to something else (that also already exists).
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.
In Rust, iterators are lazy, meaning they have no effect until you call methods that consume the iterator to use it up.
You can just use . clone() for your duplicate function.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With