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);
}
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);
}
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:
(T)
, (T, T)
, (T, T, ...)
and so on could not implement IntoIterator
. –
Pipkin T
s which, although strange, could happen as a result of generic parameters. –
Pipkin (1, "A", String::from("a"), 1.0).iter<Display>().map(|value| println!("{}", value))
–
Awning 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() { ... }
© 2022 - 2024 — McMap. All rights reserved.