Hello,
I'm trying to figure out how to do something like this (it's mostly the idea):
use std::ops::Fn;
#[derive(Default)]
struct SomeStructValue {
pub dummy: i32
}
pub type MyFn<'a, T> = Box<dyn Fn(&T) -> i32 + 'a>;
struct MyStruct<'a> {
struct_value: SomeStructValue,
my_fn: MyFn<'a, i32>
}
impl<'a> MyStruct<'a> {
pub fn new(struct_value: SomeStructValue) -> Self {
let mut my_struct = MyStruct {
struct_value,
my_fn: Box::new(|_: &i32| 0i32)
};
my_struct.my_fn = Box::new(|_: &i32| {
let value = &my_struct.struct_value;
value.dummy
});
my_struct
}
}
But the compiler (obviously) tells me:
error[E0506]: cannot assign to `my_struct.my_fn` because it is borrowed
--> src/lib.rs:22:9
|
15 | impl<'a> MyStruct<'a> {
| -- lifetime `'a` defined here
...
22 | my_struct.my_fn = Box::new(|_: &i32| {
| ^^^^^^^^^^^^^^^ --------- `my_struct.my_fn` is borrowed here
| |
| `my_struct.my_fn` is assigned to here but it was already borrowed
23 | let value = &my_struct.struct_value;
| ---------------------- borrow occurs due to use in closure
...
27 | my_struct
| --------- returning this value requires that `my_struct` is borrowed for `'a`
error[E0373]: closure may outlive the current function, but it borrows `my_struct`, which is owned by the current function
--> src/lib.rs:22:36
|
22 | my_struct.my_fn = Box::new(|_: &i32| {
| ^^^^^^^^^ may outlive borrowed value `my_struct`
23 | let value = &my_struct.struct_value;
| ---------------------- `my_struct` is borrowed here
|
note: closure is returned here
--> src/lib.rs:27:9
|
27 | my_struct
| ^^^^^^^^^
help: to force the closure to take ownership of `my_struct` (and any other referenced variables), use the `move` keyword
|
22 | my_struct.my_fn = Box::new(move |_: &i32| {
| ++++
Obviously there is a problem with the lifetime since I'm re-affecting the borrowed member to a new Box
.
I am trying to have a Fn
(not MutFn
or FnOnce
) so it means (if I'm not wrong) that all values should only be borrowed. But since the parameter passed to MyStruct::new
is moved (not borrowed). It means I need to move the argument into MyStruct
in order to be able to reference it in the Fn
. So I can only initialize my_fn
once I have a concrete address that I can reference for struct_value
.
Hoping I was clear enough, I am searching for a solution to this problem.
Thank you very much in advance for any help