Why does Iterator::take_while take ownership of the iterator?
我发现
我知道这与
为了效率起见,所有迭代器适配器都按值采用原始迭代器。 此外,拥有原始迭代器的所有权避免了不必要地处理生命周期。
如果您希望保留对原始迭代器的访问权限,则可以使用
1 2 3 4 5 6 7 8 9 10 11 12 | fn main() { let v = [1, 2, 3, 4, 5, 6, 7, 8]; let mut i1 = v.iter(); for z in i1.by_ref().take_while(|&&v| v < 4) { // ^^^^^^^^^ println!("Take While: {}", z); } for z in i1 { println!("Rest: {}", z); } } |
有输出
1 2 3 4 5 6 7 | Take While: 1 Take While: 2 Take While: 3 Rest: 5 Rest: 6 Rest: 7 Rest: 8 |
您是否注意到缺少
我使用过itertools板条箱来处理这种情况,特别是