Open
Description
When you declare closure argument types, there is no syntax to declare a lifetime parameter. And I guess lifetime elision does not apply to closures. Therefore, there seems to be no way to declare the type of a closure that returns a reference.
It compiles if you avoid declaring the type of the closure and depend on type inference. But then you would not be able to assign the closure to a local variable.
fn print_first(list: Vec<String>) {
let x: &str = list
.first()
.map(|s: &String| -> &str &s[]) // ERROR
//.map(|s: &String| &s[]) // ERROR
//.map(|s| -> &str &s[]) // ERROR
//.map(|s| &s[]) // OK
.unwrap_or("");
println!("First element is {}", x);
}
It gives a compiler error and a suggestion that does not make sense.
src/rusttest.rs:4:29: 4:32 error: cannot infer an appropriate lifetime for lifetime parameter 'a in function call due to conflicting requirements
src/rusttest.rs:4 .map(|s: &String| -> &str &s[])
^~~
src/rusttest.rs:1:1: 10:2 help: consider using an explicit lifetime parameter as shown: fn print_first<'a>(list: Vec<String>)
src/rusttest.rs:1 fn print_first(list: Vec<String>) {
src/rusttest.rs:2 let x: &str = list
src/rusttest.rs:3 .first()
src/rusttest.rs:4 .map(|s: &String| -> &str &s[]) // ERROR
src/rusttest.rs:5 //.map(|s: &String| &s[]) // ERROR
src/rusttest.rs:6 //.map(|s| -> &str &s[]) // ERROR
This bug is filed after I asked this question on stack overflow. It may be related to Region inference fails for closure parameter #17004.