How do I know the current position of the iterator?

My problem is this, but I would like to ask a slightly broader question in the title.

I have an iterator a

like Chars

another string. Suppose I find an error while reading a line, and I would like to print an error message. This message should indicate the position of the error on the line (line number, etc.). Is there any method in the Rust standard library that could help me?

+3


source to share


1 answer


You can use Iterator::enumerate()

.

Here's an example suitable for your use case:

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);
        }
    }
}

      



Prints:

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

      

+5


source







All Articles