duc*_*uck 0 iteration while-loop chars rust
我有以下代码:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
我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
Run Code Online (Sandbox Code Playgroud)
最好迭代某些东西而不是使用索引:
let mut chars = "gravy train".chars().fuse();
while let Some(c) = chars.next() {
if c == 'x' {
chars.next(); // Skip the next one
}
}
Run Code Online (Sandbox Code Playgroud)
我们fuse的迭代器可以避免next在None返回第一个之后调用任何问题.
您的代码有很多问题:
Iterator::count使用迭代器.一旦你调用它,迭代器就消失了.这是你的错误的原因.另一种解决方案是使用,Iterator::by_ref以便消耗你计算的迭代器不是行的结尾.
chars是类型Chars,不支持索引.chars[lex_index]是荒谬的.
你不能将a char与字符串进行比较,因此chars[lex_index] == "something"也不会编译.你可以使用它Chars::as_str,但是你必须自己放弃Fuse并处理它.
| 归档时间: |
|
| 查看次数: |
1066 次 |
| 最近记录: |