rustoption-typeegui

How can I mutate the contents of an optional Vec?


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.


Solution

  • You need to borrow it mutably:

    let Some(header) = &mut self.header