我有以下代码:
let mut lex_index = 0;
let chars = expression.chars();
while lex_index < chars.count() {
if(chars[lex_index] == "something") {
lex_index += 2;
} else {
lex_index += 1;
}
}
我在这里使用了一个 while
循环,因为我有时需要跳过 chars
中的一个字符。
但是,这给了我以下错误:
error[E0382]: use of moved value: `chars`
--> src/main.rs:23:15
|
23 | while i < chars.count() {
| ^^^^^ value moved here in previous iteration of loop
|
= note: move occurs because `chars` has type `std::str::Chars<'_>`, which does not implement the `Copy` trait
最佳答案
最好遍历某些东西而不是使用索引:
let mut chars = "gravy train".chars().fuse();
while let Some(c) = chars.next() {
if c == 'x' {
chars.next(); // Skip the next one
}
}
我们fuse
迭代器以避免在返回第一个 None
后调用 next
时出现任何问题。
您的代码有很多问题:
Iterator::count
消耗迭代器。调用它后,迭代器将消失。这就是你错误的原因。另一种解决方案是使用Iterator::by_ref
这样使用您计数的迭代器并不是行尾。chars
是Chars
类型,它不支持索引。chars[lex_index]
毫无意义。您不能将
char
与字符串进行比较,因此chars[lex_index] == "something"
也不会编译。您可以使用Chars::as_str
,但是你必须放弃Fuse
并自己处理它。
关于while-loop - 如何在仍然能够跳过迭代的同时迭代字符列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45122446/