rust iterate over tuple

To iterate over the elements of a tuple in Rust, you can use a for loop:

let t = (1, 2, 3, 4, 5);

for element in t.iter() {
    println!("{}", element);
}

rust iterate over tuple

This will print the elements of the tuple t on separate lines. You can also use a for loop with an enumerated iterator to get the index and value of each element:

for (i, element) in t.iter().enumerate() {
    println!("The value at index {} is {}", i, element);
}

You can also use a while loop to iterate over the elements of a tuple, like this:

let mut i = 0;
while i < t.len() {
    println!("{}", t.get(i));
    i += 1;
}

Note that tuples do not have a len method, so you will need to use the std::tuple::Tuple::get method to get the value at a particular index.

 

1 Response

  1. beaucoder says:

    No longer works in Rust 1.7.

Leave a Reply

Your email address will not be published. Required fields are marked *