How to iterate const 2d array in rust

pub const TARGET_RATES: &'static[[i32;2];3] = &[[1,1],[2,2],[3,3]];
i want to iterate over this. kindly help

Arrays can Deref-coerce to slices, so they appear to have all the methods a slice has. You can call .iter() on them to obtain an iterator, or directly write for item in array { … } if you want a procedural loop.

2 Likes

If you want to iterator over the i32 elements -- like a doubly loop in some other languages -- you can use flat_map to turn the iterator over references to the arrays into an iterator of references to the elements. And since i32 values implement Copy, you can also use .copied to turn the &i32s into just i32s, if that's what you need.

    for rarr in TARGET_RATES.iter() {
        println!("I'm a &[i32; 2]: {:?}", rarr);
    }

    for rx in TARGET_RATES.iter().flat_map(|arr| arr.iter()) {
        println!("I'm a &i32 pointing to: {}", *rx);
    }
    
    for x in TARGET_RATES.iter().flat_map(|arr| arr.iter()).copied() {
        println!("I'm an i32 with value: {}", x);
    }

Playground.

2 Likes

Or use .flatten(), since the reference to the array itself is IntoIterator.

for &x in TARGET_RATES.iter().flatten() {
    println!("I'm an i32 with value: {}", x);
}
1 Like

I see no benefit in making the constant a reference, you could just have:

pub const TARGET_RATES: [[i32;2];3] = [[1,1],[2,2],[3,3]];

If you need a reference, you can always say &TARGET_RATES.

Neither version guarantees whether or not the array will be duplicated in memory, to guarantee it's not you would need static TARGET_RATES rather than const TARGET_RATES.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.