1

According to a condition, I need to iterate on an array in one direction or another. So, I would like to iterate without knowing in which direction I am, that is why I want a variable storing an iterator.

Here some playground which does not compile : https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=956563a1b42c97333e35a1667ae135a7

fn main() {
    let array = [1, 2 , 3];
    let condition = false;

    let iter = if condition {array.iter()} else {array.iter().rev()};
    iter.for_each(|element| {/*Do something where the order matters*/});
}
  • 1
    In that case, you can put it in a `Box` to make it a [trait object](https://doc.rust-lang.org/stable/book/ch17-02-trait-objects.html). – E_net4 Jul 08 '19 at 10:18
  • I have an idea how to use different iterators with stack allocation instead of a box. Should I post it as an answer in the other question ? – Svetlin Zarev Jul 08 '19 at 10:19
  • 1
    Be sure to read all of the answers to the duplicate; the accepted one isn't necessarily exhaustive or best for your situation. – trent Jul 08 '19 at 10:21
  • 1
    @Svetlin If it is different from the existing answers, absolutely! – trent Jul 08 '19 at 10:22
  • One of the answers does indeed propose a solution which scales with multiple types and does not require heap allocations. You can also see [this other question](https://stackoverflow.com/q/28264349/1233251). – E_net4 Jul 08 '19 at 10:23
  • Thank you! I know how to do after reading all the answers to the duplicate. – David Presle Jul 08 '19 at 10:26
  • My attempt: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=c2243c74dce6aafcb4ef28054968891d, it's different than the provided answers, but hardly better. – Svetlin Zarev Jul 08 '19 at 16:36

0 Answers0