Rust 迭代器上复制和克隆的区别

Difference between copied and cloned on Rust iterators

我正在尝试找出 copied() and cloned() methods on Rust's Iterator trait. Looking at the docs on Clone 之间的区别,我可以看到它...

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.

...但是对于迭代器,这两种方法都是显式的,那么 copied() 有什么意义呢?我应该总是使用 cloned() 因为它在更一般的情况下会起作用吗?

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

通常,Rust 优化器会发现可以用更快的副本替换克隆。但是,这并不能保证,因此请尽可能使用 copied(),以确保最终得到最快的二进制文件。

我设法找到了(感谢 Peter!) this pull request,它解释了除了 cloned()...

之外还添加 copied() 的原始原因

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+)[|] [*]|&(\w+)[|] )[)]' 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.