如何在仍然可以跳过迭代的同时遍历字符列表? [英] How do I iterate over a list of chars while still being able to skip in the iteration?

查看:121
本文介绍了如何在仍然可以跳过迭代的同时遍历字符列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

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 中的一个字符。
但是,这给了我以下错误:

I use a while loop here since I sometimes need to skip a char in chars. However, this gives me the following error:

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


推荐答案

最好对某些内容进行迭代而不是使用索引:

It's better to iterate over something instead of using an index:

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 的任何问题。

We fuse the iterator to avoid any issues with calling next after the first None is returned.

您的代码有很多问题:


  1. Iterator :: count 使用迭代器。调用完之后,迭代器就会消失。这就是导致您出错的原因。另一种解决方案是使用 Iterator :: by_ref ,这样就不会消耗您计算的迭代器了。

  1. Iterator::count consumes the iterator. Once you've called that, the iterator is gone. That's the cause of your error. An alternate solution is to use Iterator::by_ref so that consuming the iterator you count isn't the end of the line.

字符的类型为 字符 ,不支持索引。 字符[lex_index] 是荒谬的。

chars is of type Chars, which does not support indexing. chars[lex_index] is nonsensical.

您不能比较 char 转换为字符串,因此 chars [lex_index] ==某物 也不会编译。您有可能可以使用 Chars: :as_str ,但随后您必须放弃 Fuse 并自己处理。

You cannot compare a char to a string, so chars[lex_index] == "something" wouldn't compile either. It's possible you could use Chars::as_str, but then you'd have to give up Fuse and deal with that yourself.

这篇关于如何在仍然可以跳过迭代的同时遍历字符列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆