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

Rustlings primitive_types3: Create an array of numbers using Ranges

Chris Biscardi
InstructorChris Biscardi
Share this video with your friends

Social Share Links

Send Tweet
Published 4 years ago
Updated 3 years ago

README for this exercise.

Chris Biscardi: [0:00] In primitive_types3, we can see that the Rust compiler expected an expression at ??? on line eight. We're supposed to create an array with at least 100 elements in it. Now, we could type out an array with 100 elements in it, but that would be quite time-consuming.

[0:14] Instead we're going to use the range. ..100 creates an array with the values through 100, incrementing by one integer, so zero, one, two, three, four, five, six, etc. Thus we have an array with greater than or equal to 100 numbers in it.

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.

Markdown supported.
Become a member to join the discussionEnroll Today