1. 16
    Rustlings primitive_types3: Create an array of numbers using Ranges
    29s

Rustlings primitive_types3: Create an array of numbers using Ranges

Share this video with your friends

Send Tweet

README for this exercise.

George Rodier
George Rodier
~ 3 years ago

I've been going through the rustlings myself and after playing around with this one, I wanted to give another example that may be more correct for anyone else that comes across this.

The example above can be solved by doing the following:

let a = [5; 100];

This creates an array of length 100 where every element is the integer 5.

The reason this may be more correct becomes apparent if you explicitly define an array type on a:

let a: [i32; 100] = [5; 100];

Here we are explicitly saying that we want a to be an array of integers of length 100. This works and compiles. However, if we follow the example in the video:

let a: [i32; 100] = 0..100;

The compiler will fail on this because it expected an array of [i32; 100] but instead found struct std::ops::Range. The reason it passes if you don't include the type is because rust will infer the type to be the range type and the range type implements the .len() method.