Welcome to Software Development on Codidact!
Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.
Why does this work? .collect() automatic conversion to function return type
I'm completing the rustlings
exercises as part of self-teaching Rust. While working on the third iterators exercise, I solved the exercise but don't quite understand why my solution works.
Specifically, I made two functions that are identical except for their name and return type, but the function body is the same in each:
// Complete the function and return a value of the correct type so the test
// passes.
// Desired output: Ok([1, 11, 1426, 3])
fn result_with_list() -> Result<Vec<i32>, DivisionError> {
let numbers = vec![27, 297, 38502, 81];
numbers.into_iter().map(|n| divide(n, 27)).collect()
}
// Complete the function and return a value of the correct type so the test
// passes.
// Desired output: [Ok(1), Ok(11), Ok(1426), Ok(3)]
fn list_of_results() -> Vec<Result<i32, DivisionError>> {
let numbers = vec![27, 297, 38502, 81];
numbers.into_iter().map(|n| divide(n, 27)).collect()
}
Some sort of automatic conversion must be occuring, likely due to Iterator::collect()
having implemented the std::iter::FromIterator
trait. Is that right or am I on the wrong track? How would I make the final type more explicit even though I don't need to, so that I can see how to do so (likely via some turbofish notation)?
1 answer
The following users marked this post as Works for me:
User | Comment | Date |
---|---|---|
qohelet | (no comment) | Feb 21, 2024 at 19:04 |
You're very much on the right track.
std::iter::FromIterator trait
This trait is indeed what makes it work. In particular, both functions' return types implement the trait:
std::result::Result<A,E>
implements it if A
implements it.[1] And here A = std::Vec
.
std::Vec
implements it as long as the iterated type matches the type contained in the Vec.[2]
Turbofish operator
Yes you can force collect
's output type with the turbofish operator:
someIter.collect::<Vec<Result<i32, DivisionError>>()
Or you don't have to specify the whole type:
someIter.collect::<Vec<Result<_>>()
someIter.collect::<Vec<_>()
If not on the returning line, you could also use type annotations
let vec_of_results: <Vec<Result<i32, DivisionError>> = someIter.collect();
0 comment threads