32

I want to iterate over a tuple using a loop, like in Python. Is it possible in Rust?

let tup1 = (1, '2', 3.0);
for i in tup1.iter() {
    println!("{}", i);
}          
Brian Bruggeman
  • 5,008
  • 2
  • 36
  • 55
Ahmed Saeed
  • 321
  • 1
  • 3
  • 4
  • 1
    [Tuples in for loops](https://users.rust-lang.org/t/tuples-in-for-loops/18321) – Trenton McKinney Aug 24 '19 at 19:10
  • 9
    "[L]ike in python and any other programming language" – I don't think there is a single statically typed programming language that lets you iterate a heterogeneous tuple type. Python is dynamically typed. – Sven Marnach Aug 24 '19 at 19:22

2 Answers2

24

The type of each element of a tuple can be different, so you can't iterate over them. Tuples are not even guaranteed to store their data in the same order as the type definition, so they wouldn't be good candidates for efficient iteration, even if you were to implement Iterator for them yourself.

However, an array is exactly equivalent to a tuple, with all elements of the same type:

let tup = [1, 2, 3];
for i in tup.iter() {
    println!("{}", i);
}

See also:

Peter Hall
  • 53,120
  • 14
  • 139
  • 204
  • 2
    I do not see why a tuple of type `(T)`, `(T, T)`, `(T, T, ...)` and so on could not implement `IntoIterator`. – mallwright Feb 06 '23 at 13:24
  • 1
    @mailwright It absolutely could be implemented. But any time you might use it you'd have to know the type at compile time, and so you could just as easily use an array. It would also be difficult to take advantage of the impl in generic contexts, except in cases where you could use the array. – Peter Hall Feb 07 '23 at 15:42
  • "you could just as easily use an array", well, unless someone's API over which you do not have control is giving you a tuple of `T`s which, although strange, could happen as a result of generic parameters. – mallwright Feb 07 '23 at 16:03
  • 1
    @PeterHall wouldn't this be useful? `(1, "A", String::from("a"), 1.0).iter().map(|value| println!("{}", value))` – Danguafer Mar 03 '23 at 19:54
-2

You can combine the tuple into an array.

const brackets: &[(&str, &str)] = &[("(", ")"), ("[", "]"), ("{", "}")];

for b in brackets.iter() {
   for c in [b.0, b.1].iter() {
      println!("{}", c);
   }
}

So technically a way to go is:

for element in [tuple.0, tuple.1, ...].iter() { ... }
Anatoly
  • 193
  • 8