Iterating over a vector of mutable references to trait objects

前端 未结 2 1440
旧巷少年郎
旧巷少年郎 2020-12-06 17:41

I have a struct that holds mutable references to trait objects:

trait Task {
    fn do_it(&mut self);
}

struct Worker<\'a> {
    task         


        
2条回答
  •  清歌不尽
    2020-12-06 18:03

    You need to have a mutable reference to each item. iter returns immutable references. And a immutable reference to a mutable variable is not itself mutable. Use iter_mut or for task in &mut self.tasks instead.

    Then, the easiest thing to do is to inline work_one into work:

    pub fn work(&mut self) {
        for task in self.tasks.iter_mut() {
            task.do_it()
        }
    }
    

    Unfortunately, splitting this into two functions is quite painful. You have to guarantee that calling self.work_one will not modify self.tasks. Rust doesn't track these things across function boundaries, so you need to split out all the other member variables and pass them separately to a function.

    See also:

    • cannot borrow `self.x` as immutable because `*self` is also borrowed as mutable
    • Why are borrows of struct members allowed in &mut self, but not of self to immutable methods?

提交回复
热议问题