1. 48
    Rustlings option2: Using if let and while let to process Optional values
    1m 29s

Rustlings option2: Using if let and while let to process Optional values

Chris Biscardi
InstructorChris Biscardi
Share this video with your friends

Social Share Links

Send Tweet

README for this exercise.

Chris Biscardi: [0:00] In option two, we have a main function that takes an optional value that we construct explicitly and a broken piece of code that doesn't run that uses the println macro to either print the value or print that the value contains nothing.

[0:12] We have a second segment of the code, but it's separate from the first where we build up a vector of options that contain IE. We instantiate this vector with the numbers from 1 to 10 using the sum constructor, using sum and the number.

[0:24] At the bottom, we have another bit of broken code. Let's look back at the first one. The intention of this code is to print a value out if a value exist, otherwise print that the optional value doesn't contain anything.

[0:34] For this purpose, we could match on the optional value, but in this case, we'll use if let. Using if let allows us to match on some value that the optional value contains.

[0:43] If it succeeds, we'll print the value having been destructured. If it doesn't, we'll print the optional value doesn't contain anything.

[0:49] This is a more concise way to write the match and allows us to not be exhaustive in our match. In the second batch of broken code. We have an optional values vector that we are popping values off. If we call pop once, it will only pop one value off, but we have 10 values in the vector.

[1:04] For this purpose, we can use while let and do the same de-structuring. While let allows us to iterate through this vector until it returns a none value and de-structure the value out of the optional_value. Note that when popping, we get an optional_value back and then the actual value in the vector can also be an optional_value.

[1:21] We have two optional_values stacked on top of each other right now. While let allows us to stack some de-structuring to the point at which we can get at the value.