Why does .step_by() expect a usize?

Viewed 98

I am trying to implement a function with nested for loops. I am having trouble with the .step_by() function, however. Here is my code:

fn get_prime_factors_below(n: i32) -> HashMap<i32, Vec<i32>> {
    for i in 2..n / 2 + 1 {
        for j in (i * 2..n).step_by(i) {
            //
        }
    }

    return factors;
}

This returns the following error when I try to compile it:

 for j in (i * 2..n).step_by(i) {
                     ------- ^ expected `usize`, found `i32`
                     |
                     arguments to this function are incorrect

Why does .step_by() expect a usize and doesn't work with an i32?

1 Answers

Using usize makes sense when you are, through some manner, performing an index lookup. If you were to try and perform an index lookup with an unsigned integer that couldn't represent numbers smaller than usize (e.g. u8) you potentially wouldn't be able to address the whole container - remember that on any system Rust targets, usize is the pointer-sized unsigned integer.

The largest step you might want to make is a usize-sized step over an iterator which occupies all your memory. If we used a larger size than this, the largest step would step into memory our system can't represent. If we used a size smaller than this, we wouldn't be able to make the biggest possible step at all!

Using this same logic, by using usize, your code can be compiled for 32 bit and 64 bit systems without having to make any changes. In this way, usize is 'correct', any other integer type can create problems for you later on.

Related