I wrote this code to test closures:
fn main() {
let test_closure = |p| p;
let ct = ClosureTest { cls: test_closure };
let s = "why".to_string();
println!("{}", (ct.cls)(&s));
}
struct ClosureTest<T>
where
T: Fn(&str) -> &str,
{
cls: T,
}
I got the following compiler error:
error[E0631]: type mismatch in closure arguments
--> src/main.rs:3:14
|
2 | let test_closure = |p| p;
| ----- found signature of `fn(_) -> _`
3 | let ct = ClosureTest { cls: test_closure };
| ^^^^^^^^^^^ expected signature of `for<'r> fn(&'r str) -> _`
|
= note: required by `ClosureTest`
error[E0271]: type mismatch resolving `for<'r> <[closure@src/main.rs:2:24: 2:29] as std::ops::FnOnce<(&'r str,)>>::Output == &'r str`
--> src/main.rs:3:14
|
3 | let ct = ClosureTest { cls: test_closure };
| ^^^^^^^^^^^ expected bound lifetime parameter, found concrete lifetime
|
= note: required by `ClosureTest`
I have a basic understanding of closures and lifetimes from the official reference site, but I couldn't find out the meaning of the compiler error message above in the reference site, especially the part about the lifetime mentioned.
It seems like the key to the error is defining a lifetime for the closure. How could I solve it?