Trying to dyanamic call a function

the big picture
1.hashmap storing multiple of Task{ taskid, cb }
2.so once i call a function it will loop through the hashmap and call the cb and pass the Task{} to it
3.cb(Task{})

but here is the problem,

  pub fn execute(&mut self) {
        for (_key, task) in &mut self.tasks {
            let task_ref = &task;
            (task.cb)(task_ref);  
        }
    }

pub struct Task {
    pub id: i32,
    pub cb: Box<dyn FnMut(&mut Task)>,
    pub recurring: bool,
    pub delay: Duration,
    pub paused: bool,
}
  let task = scheduler.add_task(
        Box::new(|id|{
             println!("Executing task with id: {}", id);
        }),
        true,
        Duration::new(5, 0),
        false,
    );

actually i want to access the Task at here not just id, if just id its okay but when i want the whole Task it just cant work, maybe refcell can solve but i tried but failed lol

error[E0308]: mismatched types
  --> src\scheduler\scheduler.rs:29:23
   |
29 |             (task.cb)(task_ref);  
   |             --------- ^^^^^^^^ types differ in mutability
   |             |
   |             arguments to this function are incorrect
   |
   = note: expected mutable reference `&mut Task`
                      found reference `&&mut Task`

it said found reference &&mut Task, but i cannot simply rewrite
let task_ref = task; it will cause another error becuase of task.cb(means if i change &Task to Task move occured after than task.cb borrowed again)

You can't have a mutable ref to Task, and then pass that mutable reference to a FnMut that is stored in Task. This requires having two mutable refs to Task at the same time, which is not allowed in Rust.

Don't store the FnMut in Task, store it separately. For example, remove cb from Task and store a pair:

(Task, Box<dyn FnMut(&mut Task)>)
2 Likes

yep thats a good idea, i think i understand what u mean thanks

also about the double mut reference rules what is the actual rules name becuase its my first to this double thing

https://doc.rust-lang.org/book/ch04-02-references-and-borrowing.html#mutable-references

Mutable references have one big restriction: if you have a mutable reference to a value, you can have no other references to that value.

I recommend studying the whole ownership section in the book if you haven't already, since mutable references are just one part of the ownership picture.

1 Like

sure thanks!

1 Like

hi bro i stucked on another question,
if you have free time can you please take a look

any ideas would be much appreciated.