Home > Software design >  Why i in for loop takes usize instead of being u64?
Why i in for loop takes usize instead of being u64?

Time:12-14

I am new into Rust and I have encountered the following issue. The following code compiles without problems, but crashes/panics during runtime leaving me with the following message: "attempt to add with overflow".

Here is the mentioned snippet:

let mut fib:[u64; 200] = [1; 200];


for i in 2..fib.len() {
   fib[i] = fib[i - 2]   fib[i - 1];
}

for i in 0..fib.len() {
   print!("{}, ", fib[i]);
}

I can't understand why the i variable looks to be of type usize and not of type u64. Thanks for your time and explanation. Somehow I could not find proper information on this.

CodePudding user response:

In iteration i = 93, the values you are trying to add are fib[91] = 7540113804746346429 and fib[92] = 12200160415121876738.

The result of this is larger than 264−1, so overflows the u64 type and the code panics.

This has nothing to do with the type of i.

  • Related