How do I make enumerate return an index as a u32 instead of usize?

Viewed 74

I see that when enumerate is called, the index value is returned as a usize. Why is this? and how can I make it return the index as another numeric type instead? Let's say u32?

Right now I have to do a manual cast to u32. For example:

let mut even_index: Vec<u32> = Vec::new();
for (i, v) in vec![10,27,31,40,5].iter().enumerate() {
    if v % 2 == 0 {
        even_index.push(i as u32); // any way to avoid this?
    }
}

Is there a way to not have to manually perform the cast to u32 and have enumerate return the index as u32 instead?

I looked at the documentation here and the documentation contains the following:

enumerate() keeps its count as a usize. If you want to count by a different sized integer, the zip function provides similar functionality.

I looked at the zip function and it looks like it does something different so I do not understand why it is being suggested as an alternative when there is a need to count by a different sized integer.

1 Answers

You can use zip and range to do:

fn main() {
    let mut even_index: Vec<u32> = Vec::new();
    for (i, v) in (0u32..).zip([10, 27, 31, 40, 5]) {
        if v % 2 == 0 {
            even_index.push(i);
        }
    }

    assert_eq!(even_index, [0, 3]);
}
Related