Confused on errors while going through option1.rs rustling

So being a newbie to rust I'm running through the rustlings, and have run into some confusion on option1.rs.

After making some tweaks, the first error I get seems obvious enough:

fn main() {

print_number(Some(13));
print_number(Some(99));

let mut numbers: [Option<u16>; 5];

for iter in 0..5 {
    let number_to_add: u16 = {
        ((iter * 5) + 2) / (4 * 16)
    };

    numbers[iter] = Some(number_to_add);
}

}

error[E0277]: the type [std::option::Option<u16>] cannot be indexed by u16
--> exercises/option/option1.rs:23:9
|
23 | numbers[iter] = Some(number_to_add);
| ^^^^^^^^^^^^^ slice indices are of type usize or ranges of usize
|
= help: the trait std::slice::SliceIndex<[std::option::Option<u16>]> is not implemented for u16
= note: required because of the requirements on the impl of std::ops::Index<u16> for [std::option::Option<u16>]

error: aborting due to previous error

So let's make it a usize. I add a line and change the index:

    let i = iter as usize;
    numbers[i] = Some(number_to_add);

But now the errors I get confuse the hell out of me:

warning: variable does not need to be mutable
--> exercises/option/option1.rs:15:9
|
15 | let mut numbers: [Option; 5];
| ----^^^^^^^
| |
| help: remove this mut
|
= note: #[warn(unused_mut)] on by default

error[E0381]: use of possibly-uninitialized variable: numbers
--> exercises/option/option1.rs:23:9
|
23 | numbers[i] = Some(number_to_add);
| ^^^^^^^^^^ use of possibly-uninitialized numbers

error: aborting due to previous error; 1 warning emitted

All from simply changing the index variable to a usize, which is what arrays want. What am I missing here?

This is on windows 10 running:
rustc 1.44.0 (49cae5576 2020-06-01)

Please format your post, it's hard to read right now. As far as I can tell, you want to create an array of Nones and then fill it one item a time, but you aren't really creating an array of Nones - you create an uninitialized array, and you can't do anything with it.

Ah. I see. That was the clue I needed.

" but you aren't really creating an array of None s - you create an uninitialized array, and you can't do anything with it."

So the issue was the array was uninitialized. So I initialize it, errors go away.

Thanks a bunch.

fn main() {
    print_number(Some(13));
    print_number(Some(99));

    let mut numbers: [Option<u16>; 5] = [None; 5];
    for iter in 0..5 {
        let number_to_add: u16 = {
            ((iter * 5) + 2) / (4 * 16)
        };

        let i = iter as usize;

        numbers[i] = Some(number_to_add);
    }
}

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.