Cannot move out of borrowed content - How to avoid clone()

Hi,
I'm implementing a struct with some methods and traits, one of them being the display trait with its method fmt(&self, f: &mut fmt::Formatter<'_>). In this method I want to loop through a borrowed vector but don't know how to do it. Minimal Code example:

struct Minimal {
    vector: Vec<u8>,
}

impl Minimal {
    fn new() -> Self {
        Minimal {vector: vec![1,2,3,4,5,6]}
    }

    fn not_working(&self) {
        for _element in self.vector {
        }
    }
}

When compiling I get the following error:

error[E0507]: cannot move out of borrowed content
  --> src/main.rs:15:23
   |
15 |         for _child in self.children {
   |                       ^^^^^^^^^^^^^ cannot move out of borrowed content

I know I can solve this by making self.clone().children, but what would be the best way to solve this?

self.children.iter() or &self.children

1 Like

Perfect, thank you!

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.