实现相同数据结构上的不同迭代器。

huangapple go评论53阅读模式
英文:

Implementing diferent iterators on same data structure

问题

我想要有选择地从迭代器中返回两个完全不同的复杂订单。(所谓的复杂订单不仅是反向和正常订单)

要实现这个目标,最好的方式是什么呢?我可以使用一个方法在事先保存状态,如下所示:

/*对于简单订单*/
data_struct_instance.select_iter(data_struct_order::Simple);
let iter_simple = data_struct_instance.iter();

/*对于复杂订单 1*/
data_struct_instance.select_iter(data_struct_order::Complex1);
let iter_complex1 = data_struct_instance.iter();

但我宁愿避免方法.select_iter()生成的内部状态。有更好的方法吗?

英文:

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.

答案1

得分: 3

使用不同的方法返回不同种类的迭代器。这是一种常见的模式,甚至在核心库中也可以找到(例如 str::charsstr::char_indices),并且具有使迭代器具有不同的返回类型而无需使用 trait 对象的优势。

一个基于你的代码的完整示例可能不太可能,但公共接口可以设计成类似以下方式:

struct DataStruct {
   // ...
}

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

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

另请参阅:

英文:

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(&amp;self) -&gt; impl Iterator&lt;SimpleData&gt; + &#39;_ {
        todo!()
    }

    pub fn complex_iter(&amp;self) -&gt; impl Iterator&lt;ComplexData&gt; + &#39;_ {
        todo!()
    }
}

See also:

huangapple
  • 本文由 发表于 2023年6月1日 00:27:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/76375587.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定