0

I have a struct and receive a reference to it in a function. I'd like to iterate over the field and if it is is None it should behave as if the Vec is empty. The best I can think of is

struct A {
    m: Option<Vec<_>>,
}

fn example(a: &A) {
    let v = vec![];
    a.m.as_ref().unwrap_or_else(|| &v).iter()
}

I don't like declaring an outside vector just to have it exist outside of unwrap_or_else.

Is there a more elegant solution?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
ditoslav
  • 4,563
  • 10
  • 47
  • 79
  • 1
    If you want it to not iterate at all when it's `None`, consider a simple `if let Some(x) = checks { /* iterate over x */ }`, or consider the answers on this thread: [Iterator on Option>](https://stackoverflow.com/q/40907897/5923139) – Aplet123 Jun 09 '21 at 18:27
  • 1
    Apologies for introducing additional noise in the code. I've added an explanation that if the Option is None I want to pretend as if the Vec is empty meaning the iter wouldn't iterate over any elements. @Aplet123 answered my question – ditoslav Jun 09 '21 at 18:30
  • 1
    [alternative solution](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=ea41586896892f1bbc781276db7dc604) – Ömer Erden Jun 09 '21 at 18:35
  • @Aplet123 I think it's reasonable to explicitly add your `if let` answer to the question you linked. – Shepmaster Jun 09 '21 at 19:37

0 Answers0