0

I'm trying to implement an iterator for a struct:

struct A {
    x: Option<String>,
    y: Option<String>,
    z: String,
    index: usize,
}

impl Iterator for A {
    type Item = String;
    fn next(&mut self) -> Option<Self::Item> {
        let result = match self.index {
            0 => /* **magic deciding thing for self.x** */,
            1 => /* **magic deciding thing for self.y** */,

            2 => String,
            _ => return None,
        };
        self.index += 1;
        Some(result)
    }
}

Is there any way to always increment index, and then exit the function if the value in x or y is None, otherwise unwrap Some() and carry on as usual? There are no default values I can return.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Pranav Bhatt
  • 125
  • 1
  • 11
  • The [duplicates applied to your case](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=8528b40a6ef5f4c0b6704621b23af286) – Shepmaster Apr 15 '20 at 18:09
  • Do [you mean this](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=a206300ea9c89934ffe53f3508737ac3) or [this](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=942f6232cd95f6152bd27d844584e370)? – Shepmaster Apr 15 '20 at 18:45
  • 1
    You might also want `.take()` instead of `.clone()` for `x` and `y`, although I'm not sure what you're going to do with `z`. – trent Apr 15 '20 at 20:08
  • 1
    @trentcl in that case, [you can use `mem::take`](https://stackoverflow.com/a/41370552/155423) :-) – Shepmaster Apr 15 '20 at 20:32
  • I think [this](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=a206300ea9c89934ffe53f3508737ac3) is exactly what I needed! Thank you so much! – Pranav Bhatt Apr 16 '20 at 04:38
  • Or use [combinators](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=729b52576fcdf963bfaa3cbd506bbd6f). – L117 Apr 16 '20 at 08:54

0 Answers0