Consider the following code (or run it in rust playground here):
1 2 3 4 5 6 7 |
fn main() { let a:Vec<u32> = vec![1, 2, 3]; let doubled = a.iter().map(|&x| x * 2).collect(); assert_eq!(vec![2, 4, 6], doubled); } |
If you ran it in the playground linked above, you will see the following compiler error.
1 2 3 4 5 6 7 8 9 10 11 12 |
error[E0282]: type annotations needed --> src/main.rs:4:9 | 4 | let doubled = a.iter().map(|&x| x * 2).collect(); | ^^^^^^^ consider giving `doubled` a type error: aborting due to previous error For more information about this error, try `rustc --explain E0282`. error: could not compile `playground` To learn more, run the command again with --verbose. |
Because collect() is so general, it can cause problems with type inference. As such, collect() is one of the few times you’ll see the syntax affectionately […]