Search code examples
rustsyntaxdestructuring

Parallel iteration over same index items of lists | Syntax Question


Learning Rust, one of the coolest things I've noticed is how often it is intuitive to use destructuring. I'm currently working on a problem that involves iteration over two lists and comparing elements that have the same index. I find myself wishing I had some kind of syntax similar to

for (possible_item, possible_other_item) in (list1.iter(), list_two.iter()) 
{
   // Do stuff with the items. 
   // possible_item and possible_other_item would be Option types 
   // In case list1 and list2 had different lengths  
}

Does anyone know of something similar to this in any programming language? In rust you can destructure HashMaps as (key, value) tuples, so I feel like this syntax is possible to implement.


Solution

  • You can try using zip to combine the elements from each collection.

    pub fn main( ) {
        let v1 = vec![ 1, 2, 3, 4, 5 ];
        let v2 = vec![ 6, 7, 8, 9, 10 ];
    
        for ( i1, i2 ) in v1.iter( ).zip( v2.iter( ) ) {
            println!( "v1 value: {} | v2 value: {}", i1, i2 );
        }
    
        // Prints out.
        // v1 value: 1 | v2 value: 6
        // v1 value: 2 | v2 value: 7
        // v1 value: 3 | v2 value: 8
        // v1 value: 4 | v2 value: 9
        // v1 value: 5 | v2 value: 10
    }
    

    Note that if the collections aren't symmetrical it'll skip those elements.

    pub fn main( ) {
        let v1 = vec![ 1, 2, 3, 4, 5 ];
        let v2 = vec![ 6, 7, 8, 9, 10, 11 ];
    
        for ( i1, i2 ) in v1.iter( ).zip( v2.iter( ) ) {
            println!( "v1 value: {} | v2 value: {}", i1, i2 );
        }
    
        // Notice that it did not print 11 from the v2 vector.
        // v1 value: 1 | v2 value: 6
        // v1 value: 2 | v2 value: 7
        // v1 value: 3 | v2 value: 8
        // v1 value: 4 | v2 value: 9
        // v1 value: 5 | v2 value: 10
    }