Is there a way to find out how many iterations we did in a for loop?

Is there an easy way to find out how many iterations we did in a for loop?

If i have this code

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

How can I easily get a linenumber number? Should I use an external counter variable?

+5
source share
1 answer

It should be simple:

 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. The advantage of this is that you can change things such as the start and numbering steps, as well as the number of items zipped.

+6
source

All Articles