#Iterating over traits

10 messages · Page 1 of 1 (latest)

orchid cliff
#

I am trying to get the following working, specifically the render function, but cannot for the life of me work it out,



fn main() {
    let mut entities = Entities::new();
    let mut square = Square { i: 0 };
    entities.push(&mut square);
    let mut square = Square { i: 1 };
    entities.push(&mut square);
}

trait Renderable {
    fn render(&mut self);
}

struct Entities<'a> {
    entities: Vec<&'a dyn Renderable>,
}

impl<'a> Entities<'a> {
    pub fn new() -> Self {
        Self {
            entities: Vec::new(),
        }
    }
    pub fn push(&mut self, entity: &'a mut dyn Renderable) {
        self.entities.push(entity);
    }

    pub fn render(&mut self) {
        for e in self.entities.iter_mut() {
            e.render();
        }
    }

    // bonus points
    pub fn entities_iter(&mut self) -> impl Iterator<Item = &dyn Renderable> {

    }
}

struct Square {
    i: u32,
}

impl Renderable for Square {
    fn render(&mut self) {
        self.i += 1
    }
}
#

I have tried the rust playground to paste this, but it appears to be down

#

THis is erroring in the Entities::render:

#

error[E0596]: cannot borrow **e as mutable, as it is behind a & reference

   |
29 |             e.render();
   |             ^^^^^^^^^^ cannot borrow as mutable
jolly zephyr
#

Your struct holds & references:

entities: Vec<&'a dyn Renderable>,
```so that makes the type of `e: &mut &dyn Renderable`. Just change that to `Vec<&'a mut dyn Renderable>` and it should work.
orchid cliff
#

Seaish, you are right, thank you!

#

is there any way to get the fn entities_iter return an iterable?

#

having the entities as pub works, but...

jolly zephyr
#

You can change it to returning &mut in the iterator and do self.entities.iter(). Or maybe leave the return the same and have it take &self (not 100% sure if that works). Or leave it the same and do self.entities.iter().map(|r| &*r).

orchid cliff
#

ok, thanks. I tried a couple of variations, and ended up fighting the compiler, probably due to lifetime issues of references, but I'll try them