如何知道迭代器的当前位置?

时间:2015-05-26 14:27:24

标签: rust

我的问题如下,但我想问一下标题中稍微宽泛的问题。

我有一个a类型的迭代器Chars,其他字符串。假设我在读取字符串时发现错误,并且我想打印错误消息。这条消息应该提到错误在字符串中的位置(行号等)。在Rust标准库中有什么方法可以帮助我吗?

1 个答案:

答案 0 :(得分:5)

您可以使用Iterator::enumerate()

以下是针对您的用例量身定制的示例:

fn one_indexed<T>((n, x): (usize, T)) -> (usize, T) {
    (n+1, x)
}
fn main() {
    let s = "abc def\nghi jkl";
    for (line_n, line) in s.lines().enumerate().map(one_indexed) {
        for (char_n, char) in line.chars().enumerate().map(one_indexed) {
            println!("character {} at {}:{}", char, line_n, char_n);
        }
    }
}

打印:

character a at 1:1
character b at 1:2
character c at 1:3
character   at 1:4
character d at 1:5
character e at 1:6
character f at 1:7
character g at 2:1
character h at 2:2
character i at 2:3
character   at 2:4
character j at 2:5
character k at 2:6
character l at 2:7