我试图找出 copied()
之间的区别和 cloned()
Rust 的 Iterator
上的方法特征。查看 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()
因为它适用于更一般的情况?
最佳答案
我设法找到了(感谢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+)[|] [*]\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.
关于rust - Rust 迭代器上复制和克隆的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58413583/