1. 54
    Rustlings iterators3: Iterating and collecting values using the IntoIter trait
    2m 9s

Rustlings iterators3: Iterating and collecting values using the IntoIter trait

Chris Biscardi
InstructorChris Biscardi
Share this video with your friends

Social Share Links

Send Tweet

README for this exercise.

into_iter is an implementation of the IntoIter trait for vectors. In this case the implementation calls out to iter() under the hood.

Chris Biscardi: [0:00] In iterators3, we need to both complete the divide() function to get the first four tests to pass. Then uncomment the last two tests and fill in values for x in the last few tests using the division_results in those two tests.

[0:13] We'll start with the divide() function. The divide() function is a public function that takes two integers and returns a result that is either an integer or a DivisionError. You could see that DivisionError is defined in the same file and as an enum that can either be NotDivisible with an argument of NotDivisibleError or DividedByZero Err.

[0:31] In addition, the comment above the divide() function says that we should calculate 'a' divided by 'b' only if 'a' is evenly divisible by 'b'. Otherwise, it should return a suitable error. First, we can test the if b == . If it is, then we need to return an Err(DivisionError: :DividedByZero). Otherwise, if a is divisible by b, with no remainder, we can return the division of a/b.

[0:54] Finally, if neither of those count, we can return a DivisionError. The DivisionError takes a struct, but as a non-divisible error of the dividend and the divisor.

[1:04] Now that we've passed the first four tests, we'll pass the next two. We'll uncomment the second to last test and fill an x here. Now that we have numbers which are a vec! Of four different numbers, and we have division_results in which we take numbers, which we put into an iterator, and then map over with our divide() function.

[1:21] This leaves us with division_results which is delimiter, so we know we need to collect it. If we look at the assert_eq!, we can see that we're expecting a result type that wraps the values that were divided. We want a result that is either a Vec of i32s or the error type.

[1:36] We know this is the return value because this is the return value that divide gives us, except for the fact that the i32 are not in a vector when we turn it from divide. They're in a vector now because we operated over a vector, so divide was applied to each individual number. The type Result which can either return a vector by i32s that we divided over or over DivisionError.

[1:57] We can do the same thing for the last test using the same code, but this time, the return type is different. Here we have a Vec of Result types. What we need to do here is pull the Vec out and collect. We'll know how to collect this into it, and our tests are passing.