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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With