-1

I'm trying to learn rust with egui, and I'm trying to make a list of checkboxes.

struct Checkbox {
    check: bool,
    text: String
}

Eventually, the borrow checker doesn't like this code:

// There is a parameter &mut self
// self.header: Option<Vec<Checkbox>>
if let Some(header) = &self.header {
    for i in 0..header.len() - 1 {
        ui.checkbox(&mut header[i].check, header[i].text);
    }
}

The compiler says cannot borrow '*header' as mutable, as it is behind a '&' reference in the for loop (ui.checkbox line), which kind of makes sense, but I'm not sure what the workaround is. I get the same error if I use for head in header.into_iter() {. And, of course, I tried using let Some(header) = self.header, but that gives cannot move out of 'self.header.0' which is behind a mutable reference.

Kenkron
  • 573
  • 1
  • 3
  • 15
  • From the error I understand self is already borrowed mutable, you cannot use `into_iter` since it will try to change the ownership of the `vec`, looks like you don't really need an ownership, instead you can use `iter_mut` to get items as mutable: `header.iter_mut().for_each(|item |ui.checkbox(item.check, item.text))` – Ömer Erden Aug 29 '22 at 06:34
  • Does this answer your question? [How can I do a mutable borrow in a for loop?](https://stackoverflow.com/questions/39622783/how-can-i-do-a-mutable-borrow-in-a-for-loop) – Ömer Erden Aug 29 '22 at 06:39

1 Answers1

3

You need to borrow it mutably:

let Some(header) = &mut self.header
FZs
  • 16,581
  • 13
  • 41
  • 50
Chayim Friedman
  • 47,971
  • 5
  • 48
  • 77