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

标签 rust iterator copy clone

我试图找出 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/

相关文章:

rust - 如何在方法实现中从枚举中的字符串返回 &str?

rust - 可以在集成测试中编译依赖于std的 crate ,从而在可执行文件的库部分中引入一些std的隐式用法吗?

rust - 我如何将 'pass down' 功能标志标记为 Cargo 中的子依赖项?

rust - 未为f64实现RawData

C++ - 迭代从 find_if 返回的 std::vector<>

python - 为什么 Python 使用异常来管理迭代器,而其他语言为什么不用呢?

java - 在 Linux/Java 中调度文件/文件夹复制的应用程序

python - 在 Pandas 中过滤数据框时复制警告

java - 复制 AST 中的节点

C++ vector 迭代器 nth_element 编译错误