while-loop - 如何在仍然能够跳过迭代的同时迭代字符列表?

标签 while-loop rust iteration chars

我有以下代码:

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 时出现任何问题。


您的代码有很多问题:

  1. Iterator::count消耗迭代器。调用它后,迭代器将消失。这就是你错误的原因。另一种解决方案是使用 Iterator::by_ref这样使用您计数的迭代器并不是行尾。

  2. charsChars 类型,它不支持索引。 chars[lex_index] 毫无意义。

  3. 您不能将 char 与字符串进行比较,因此 chars[lex_index] == "something" 也不会编译。您可以使用 Chars::as_str ,但是你必须放弃 Fuse 并自己处理它。

关于while-loop - 如何在仍然能够跳过迭代的同时迭代字符列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45122446/

相关文章:

r - For 语句嵌套在 while 语句中不起作用

closures - 为闭包类型别名实现特征

python - 第 60 行,在 make_tuple 中返回 tuple(l) TypeError : iter() returned non-iterator of type 'Vector'

java - 更改 Map 的迭代顺序

C 使用 while 循环添加输入

c - do {} while 不会终止

matlab - 循环语句性能和预分配循环语句本身

rust - 返回 Option 时有些不需要?

rust - 从Rust的扫描码中检索与键盘布局无关的键入字符

c - 汉诺塔的实现——迭代过程