Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to know how many iterations we have done in a for loop?

Tags:

rust

Is there an easy way to know how many iteration we have done in a for loop?

If I have this code

for line in lines {
    println!("{}: {}", linenumber, line);
}

How can I easily get the number linenumber? Am I required to use an external counter variable?

like image 239
Mathieu David Avatar asked May 31 '15 11:05

Mathieu David


1 Answers

It should be as simple as:

for (linenumber, line) in lines.enumerate() {
    println!("{}: {}", linenumber, line);
}

You can also do

#[macro_use]
extern crate itertools;

fn main() {
    for (linenumber, line) in izip!(0.., lines) {
        println!("{}, {}", linenumber, line);
    }
}

for more flexibility. This has the advantage of letting you change things like the start and step of the numbering as well as the number of zipped elements.

like image 130
Veedrac Avatar answered Oct 01 '22 04:10

Veedrac