I have a const array FUNCS
which holds references to some methods in a struct MyStruct<'a>
. I want to use this const array inside a method of MyStruct
, but I get the error "cannot infer an appropriate lifetime due to conflicting requirements". There are some conflicts between 'a
and 'static
, but I can't solve it.
If I use the const array outside the struct implementation (eg in main()
), it's working.
How can I use this array inside the struct implementation?
Code:
type Func<'a> = fn(&MyStruct<'a>);
const FUNCS: [Func; 2] = [
MyStruct::one,
MyStruct::two,
];
struct MyStruct<'a> {
s: &'a str,
}
impl<'a> MyStruct<'a> {
fn use_func(&self, n: usize) {
let f = FUNCS[n]; // error
f(self);
}
fn one(&self) {
println!("{}", self.s.len());
}
fn two(&self) {
println!("{}", self.s.len() * 2);
}
}
fn main() {
let p = MyStruct { s: "hi" };
p.use_func(1);
// If use_func() is commented, the code below is working:
let f = FUNCS[0];
f(&p);
}
Error report:
error[E0495]: cannot infer an appropriate lifetime due to conflicting requirements
--> src/main.rs:14:17
|
14 | let f = FUNCS[n];
| ^^^^^^^^
|
note: first, the lifetime cannot outlive the lifetime `'a` as defined on the impl at 12:6...
--> src/main.rs:12:6
|
12 | impl<'a> MyStruct<'a> {
| ^^
note: ...so that the expression is assignable
--> src/main.rs:15:11
|
15 | f(self);
| ^^^^
= note: expected `&MyStruct<'_>`
found `&MyStruct<'a>`
= note: but, the lifetime must be valid for the static lifetime...
note: ...so that the expression is assignable
--> src/main.rs:14:17
|
14 | let f = FUNCS[n];
| ^^^^^^^^
= note: expected `for<'r> fn(&'r MyStruct<'_>)`
found `for<'r> fn(&'r MyStruct<'static>)`
For more information about this error, try `rustc --explain E0495`.
error: could not compile `basic-test` due to previous error