Why does this, with no type annotation on the closure, compile?
fn transform(input: &Vec<Vec<String>>) {
input.iter().flat_map(|words| words.iter());
}
But this doesn't?
fn transform(input: &Vec<Vec<String>>) {
input.iter().flat_map(|words: &Vec<String>| words.iter());
}
Is the inferred type not &Vec<String>
? Or do I need to annotate the lifetime too, as this seems to be about the closure not living long enough?
The error for in the latter snippet is
error[E0495]: cannot infer an appropriate lifetime for lifetime parameter in function call due to conflicting requirements
--> src/main.rs:2:55
|
2 | input.iter().flat_map(|words: &Vec<String>| words.iter());
| ^^^^
|
note: first, the lifetime cannot outlive the anonymous lifetime #1 defined on the block at 2:48...
--> src/main.rs:2:49
|
2 | input.iter().flat_map(|words: &Vec<String>| words.iter());
| ^^^^^^^^^^^^
note: ...so that reference does not outlive borrowed content
--> src/main.rs:2:49
|
2 | input.iter().flat_map(|words: &Vec<String>| words.iter());
| ^^^^^
note: but, the lifetime must be valid for the method call at 2:4...
--> src/main.rs:2:5
|
2 | input.iter().flat_map(|words: &Vec<String>| words.iter());
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
note: ...so type `fn(std::slice::Iter<'_, std::vec::Vec<std::string::String>>, [closure@src/main.rs:2:27: 2:61]) -> std::iter::FlatMap<std::slice::Iter<'_, std::vec::Vec<std::string::String>>, std::slice::Iter<'_, std::string::String>, [closure@src/main.rs:2:27: 2:61]> {<std::slice::Iter<'_, std::vec::Vec<std::string::String>> as std::iter::Iterator>::flat_map::<std::slice::Iter<'_, std::string::String>, [closure@src/main.rs:2:27: 2:61]>}` of expression is valid during the expression
--> src/main.rs:2:5
|
2 | input.iter().flat_map(|words: &Vec<String>| words.iter());
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^