1

I want initialize multiple variables in a for loop, like for example something like this: for (i, j) in (1..=4),(10..=16).step_by(2){ println!("i = {i}, j ={j}"); }

The result would be something like: i = 1, j = 10 i = 2, j = 12 i = 3, j = 14 i = 4, j = 16

I have checked this post: How to use multiple variables in Rust's for loop? but I haven´t found anything useful for me, I know I can use a while loop, but I find the ability to set everything in just one line much clearer

THB
  • 11
  • 3

1 Answers1

4

The zip iterator method, mentioned in the very answer you link to, creates tuples by pairing up elements of two iterators. You can still use it all on one line; there is nothing that requires you to create the two iterators as separate statements.

for (i, j) in (1..=4).zip((10..=16).step_by(2)) {
    println!("i = {i}, j ={j}");
}

(Playground)

cdhowie
  • 158,093
  • 24
  • 286
  • 300
  • 1
    Thank you so much, I also learned about the izip! iterator tool (https://stackoverflow.com/questions/29669287/how-can-i-zip-more-than-two-iterators) which makes it look cleaner and allows to do this with more than 2 iterators. (https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=e1fe7cd8059b9ac8ce7b0c1a36f54645) – THB Jan 18 '23 at 23:10