Consider this code:
struct WithLifetime<'a> {
s: &'a str
}
impl WithLifetime<'_> {
fn in_impl(&self) -> bool {
self.s == "a"
}
}
fn out_of_impl(wl: &WithLifetime<'_>) -> bool {
wl.s == "a"
}
fn higher_order(f: fn(&WithLifetime<'_>) -> bool) -> bool {
let s = "a";
let wl = WithLifetime { s };
f(&wl)
}
fn main() {
higher_order(out_of_impl); // This line compiles
higher_order(WithLifetime::in_impl); // This line does not
}
The final line of main
fails to compile with this error:
error[E0308]: mismatched types
--> src/main.rs:23:18
|
23 | higher_order(WithLifetime::in_impl); // This line does not
| ^^^^^^^^^^^^^^^^^^^^^ one type is more general than the other
|
= note: expected fn pointer `for<'r, 's> fn(&'r WithLifetime<'s>) -> _`
found fn pointer `for<'r> fn(&'r WithLifetime<'_>) -> _`
As far as I can figure out, in_impl
and out_of_impl
should be exactly the same function. They both take a reference to a WithLifetime
, and don't care about the lifetime of that reference or the lifetime parameter of the WithLifetime
instance. Both should be valid parameters to pass to higher_order
. The compiler does not agree.
What is the problem with passing in_impl
to higher_order
, and why doesn't the compiler allow this? What can I do to pass struct methods on structs with lifetime parameters to higher-order functions?