Is it possible to iterate over a tuple?
Asked Answered
L

2

39

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);
}          
Lassie answered 24/8, 2019 at 19:0 Comment(2)
Tuples in for loopsEnscroll
"[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.Lariat
F
29

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:

Faucher answered 24/8, 2019 at 19:16 Comment(4)
I do not see why a tuple of type (T), (T, T), (T, T, ...) and so on could not implement IntoIterator.Pipkin
@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.Faucher
"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 Ts which, although strange, could happen as a result of generic parameters.Pipkin
@PeterHall wouldn't this be useful? (1, "A", String::from("a"), 1.0).iter<Display>().map(|value| println!("{}", value))Awning
L
-1

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() { ... }
Laity answered 26/8, 2021 at 17:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.