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.
Post History
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. Specifi...
Question
rust
#1: Initial revision
Why does this work? .collect() automatic conversion to function return type
I'm completing [the `rustlings` exercises](https://rustlings.cool/) as part of self-teaching Rust. While working on [the third iterators exercise](https://github.com/rust-lang/rustlings/blob/main/exercises/18_iterators/iterators3.rs), 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()`](https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.collect) having implemented the [`std::iter::FromIterator` trait](https://doc.rust-lang.org/std/iter/trait.FromIterator.html). 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)?