我找到了一段正在使用的代码 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 夜间事件中发生了一些变化,导致弹出这个新错误:
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
等方法一起使用的正确方法是什么?
最佳答案
您不需要克隆底层数据(字节
),但您需要克隆迭代器:
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,所以你需要明确 Clone
这在 this commit 中发生了变化, 当 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.
另见:
关于rust - 我如何借用迭代器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28615756/