简体   繁体   中英

Is it possible to iterate over a tuple?

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

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

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:

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() { ... }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM