知识卡片

普通读书笔记卡 · 743.d.6.a.2

迭代是否消耗取决于接收类型

理解等级:中级

for item in collection对Vec通常取得所有权并逐项移出;for item in &collection则消耗的是共享引用,产出元素引用,集合仍在。&mut collection产出可变引用,需相应实现。into_iter消费Self不等于总会消费集合本体;iter与iter_mut把借用意图表达得更直接。

这张卡片看不懂?

已有反馈 · 0 / 10 条

    还没有人提交反馈。

    在整书笔记中的位置

    原书出处 · 1 处

    • Chapter 1. Types Iterator Traits · 查看原书依据

      Self is &Collection rather than Collection, and the associated Item type will be a reference &Thing. This leaves the collection intact after iteration, and the equivalent expanded code is as follows: let mut iter = (&collection).into_iter(); while let Some(item) = iter.next() { println!("{}", item.0); } If it makes sense to provide iteration over mutable ref

    参考来源

    - 位置:《Effective Rust 35 Specific Ways to Improve Your Rust Code (David Drysdale)》第1章《Iterator Traits》(spine5;extracted/Effective Rust 35 Specific Ways to Improve Your Rust Code (David Drysdale)/_epub-src/OEBPS/ch01.html;u048-ch01-073)。 - 结论依据:原文在“Self is &Collection”附近的定义、例子或代码支撑本卡核心说明:for item in collection对Vec通常取得所有权并逐项移出;for item in &collection则消耗的是共享引用,产出元素引用,集合仍在。边界按已读前提解释;示例未执行。 - 原始内容:Self is &Collection rather than Collection, and the associated Item type will be a reference &Thing. This leaves the collection intact after iteration, and the equivalent expanded code is as follows: let mut iter = (&collection).into_iter(); while let Some(item) = iter.next() { println!("{}", item.0); } If it makes sense to provide iteration over mutable ref