-1

I want to have the option to return 2 completely different complex orders from an iterator. (referring to complex as not only reversed and normal order)

What would be the best way to accomplish this, i could have a method that saves the state before hand like:

/*for simple order*/
data_struct_instance.select_iter(data_struct_order::Simple);
let iter_simple = data_struct_instance.iter();

/*for complex order 1*/
data_struct_instance.select_iter(data_struct_order::Complex1);
let iter_complex1 = data_struct_instance.iter();

But i would rather avoid the internal state generated by the method .select_iter() is there a better way to accomplish this.

GumGun
  • 37
  • 4

1 Answers1

3

Use different methods returning different kinds of iterators. It is a common pattern, even found in the core library (see e.g. str::chars and str::char_indices), and comes with the advantage of enabling different return types for iterators without trait objects.

A complete example based on your code is not possible, but the public interface could be made into something like this:

struct DataStruct {
   // ...
}

impl DataStruct {
    pub fn simple_iter(&self) -> impl Iterator<SimpleData> + '_ {
        todo!()
    }

    pub fn complex_iter(&self) -> impl Iterator<ComplexData> + '_ {
        todo!()
    }
}

See also:

E_net4
  • 27,810
  • 13
  • 101
  • 139
  • An other example is `Vec` having 4 different iterators (iter and iter_mut from slices, into_iter, and drain), or HashMap with 8 (iter, iter_mut, into_iter, keys, into_keys, values, values_mut, into_values, and drain). – Masklinn May 31 '23 at 17:01