Search code examples
castingrustoption-typeownershipinference

Understanding type inference


I believe I am having a problem with both the data type and ownership of iter. It is first declared inside the for loop expression. I believe Rust infers that iter is of type u16 because it is being used inside of my computation on line 4.

  1     let mut numbers: [Option<u16>; 5];                                          
  2     for iter in 0..5 {                                           
  3         let number_to_add: u16 = {  // `iter` moves to inner scope                                            
  4             ((iter * 5) + 2) / (4 * 16)  // Infers `iter: u16`                                 
  5         };                                                                   
  6                                                                                 
  7         numbers[iter] = Some(number_to_add);  // Expects `iter: usize`                 
  8     }      

I am receiving the following error:

error[E0277]: the type `[std::option::Option<u16>]` cannot be indexed by `u16`
  --> exercises/option/option1.rs:3:9
   |
7  |         numbers[iter] = Some(number_to_add);
   |         ^^^^^^^^^^^^^ slice indices are of type `usize` or ranges of `usize`
  • I tried casting iter as u16 inside the computation in line 4, but still having issues.

Where is my misconception?


Solution

  • Your assumption is correct. And your fix was ok too (it led to a different error, see below).

    Your first problem was that for slice indexing, iter needs to be of type usize so either

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

    or

    ((iter as u16 * 5) + 2) / (4 * 16)
    

    will lead to correct type inference through rustc.

    Your second problem was that numbers was not initialized, so rustc correctly warns you when you try to modify numbers. Assigning a value, e.g.,

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

    will let you compile your program.