1. 47
    Rustlings option1: Introducing the Option type
    1m 28s

Rustlings option1: Introducing the Option type

Chris Biscardi
InstructorChris Biscardi
Share this video with your friends

Social Share Links

Send Tweet
Published 4 years ago
Updated 4 years ago

README for this exercise.

Chris Biscardi: [0:00] In option1, we have a print_number() function that takes maybe_number which is an Option<u16>. The println! Unwraps the maybe_number and prints the value.

[0:10] We use print_number() on two numbers. Then we also have a separate, unrelated piece of code that is a mut numbers array that contains the Option<u16> 5 times.

[0:21] In this case, we haven't yet initialized numbers. We iterate over the range zero to five, and let number_to_add which is a u16 equals to math. Then, we set the value at the index that the iteration specifies in numbers to the number_to_add value.

[0:35] The first issue that the Rust compiler tells us about is that it expected enum 'Option' and found integer when we're trying to call print_number(13). This is because the function takes an option value which we can instantiate with Some.

[0:49] While fixes most of our problems up top, on line 19, indexes into arrays cannot be of type u16. We'll treat this as a usize. Also note that on line 19, the number_to_add needs to be an Option value, so we'll instantiate that with Some as well.

[1:04] Finally, we have a warning and another error. The Rust compiler tells us that we're using a possibly-uninitialized 'numbers' array on line 19.

[1:12] This is true, and we can instantiate this numbers array with a set of default values using similar syntax that we used to specify the size of the array in the type signature.

[1:23] We now have a numbers array that is mutable and contains none values for all five values.