How do I turn an Option<&mut T> into an iterator?

I would like a mutable iterator over options.

The only way I made it work is by calling take() on the option but that is not what I want. I want Thing to be reusable.

struct Thing<'a> {
    opt: Option<&'a mut usize>,
}

impl<'a> Thing<'a> {
    fn new(opt: Option<&'a mut usize>) -> Self {
        Self {
            opt,
        }
    }

    fn iter_mut(&mut self) -> impl Iterator<Item = &mut usize> {
        // this is wrong! I want to keep the Option's content as is.
        self.opt.take().into_iter()
    }
}

fn main() {
    let mut num = 64;
    let mut thing = Thing::new(Some(&mut num));

    println!("{:?}", thing.iter_mut().collect::<Vec<_>>());
}

playground

fn iter_mut(&mut self) -> impl Iterator<Item = &mut usize> {
    self.opt.as_deref_mut().into_iter()
}
3 Likes

Thank you so much. Really appreciate it. :slight_smile: