Search code examples
rustiteratorcopyclone

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?


Solution

  • 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.