Array iteration

Ive been searching for over an hour on how to simply loop through an array and update all values based on the array's index. Ive gotten all kinds of compile errors as I try various different methods to get this to work, basically my types are not right. I can only assume the type of the index of an array is not usize, but u8 in my example below. I will also assume you can't simply typecast in Rust either. I would greatly appreciate any insight on how to perform such a simple task.

let mut array = [0u8; 20];

for i in range(0, array.len()) {
array[i] = i + array[i];
}

1 Like

You need to use the std::num::ToPrimitive trait, and convert:

use std::num::ToPrimitive;

fn main() {
    let mut numbers = [1u8, 2, 3, 4, 5, 6];
    println!("before: {:?}", numbers);
    for i in range(0, numbers.len()) {
        let x = i.to_u8().unwrap();
        numbers[i] = x + numbers[i];
    }
    println!("after: {:?}", numbers);
}
1 Like

No need for that - i as u8 should work fine.

1 Like

As @comex says, you can use as to cast between primitive numeric types.

I personally might write the loop as:

for (i, elem) in array.iter_mut().enumerate() {
    *elem += i as u8
}

which leverages iterators, and the various methods defined on them (e.g. enumerate in this case).

5 Likes

That truncates the integer though, making potential integer overflow invisible. to_u8().unwrap() is the safer (albeit unfortunately longer) method.

1 Like

Thanks folks for the replies. This should get me started.

Depends on the intended semantics. In any case, as will have debug assertions just like the rest of the primitive operations.

Thanks for pointing out enumerate! It greatly simplifies some of my code. I love it :smile: