我如何借用迭代器?

How do I borrow an Iterator?

我找到了一段正在使用的代码 in another Stack Overflow question

fn is_palindromic(num: i64) -> bool {
    let string = num.to_string();
    let bytes = string.as_bytes();
    let iter = bytes.iter();
    let n = bytes.len() / 2;
    equals(iter.take(n), iter.rev().take(n))
}

当我最初发现它时它工作正常,但在 2015 年 1 月 30 日和 2012 年 2 月 17 日之间的 Rust nightlies 中发生了一些变化,导致弹出这个新错误:

src/program.rs:8:26: 8:30 error: use of moved value: `iter`
src/program.rs:8     equals(iter.take(n), iter.rev().take(n))
                                          ^~~~
src/program.rs:8:12: 8:16 note: `iter` moved here because it has type `core::slice::Iter<'_, u8>`, which is non-copyable
src/program.rs:8     equals(iter.take(n), iter.rev().take(n))
                            ^~~~

我查看了文档,但似乎找不到任何表明可能已更改的内容。 take 方法现在的行为似乎有所不同,但我不确定如何解决克隆 bytes 和使用两个单独的迭代器的情况。

这似乎是一种非常低效的解决看似相当普遍的问题的方法,所以我想我可能遗漏了一些东西。

std::iter::order::equals这样的方法借用迭代器的正确方法是什么?

您不需要克隆底层数据 (bytes),但您确实需要克隆迭代器:

fn is_palindromic(num: i64) -> bool {
    let string = num.to_string();
    let bytes = string.as_bytes();
    let iter = bytes.iter();
    let n = bytes.len() / 2;
    equals(iter.clone().take(n), iter.rev().take(n))
}

迭代器不是隐含的Copy-able, so you need to explicitly Clone它。

这在 this commit, when IntoIterator was introduced 中发生了变化:

This PR also makes iterator non-implicitly copyable, as this was source of subtle bugs in the libraries. You can still use clone() to explictly copy the iterator.

另请参阅: