英文:
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::chars
和 str::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(&self) -> impl Iterator<SimpleData> + '_ {
todo!()
}
pub fn complex_iter(&self) -> impl Iterator<ComplexData> + '_ {
todo!()
}
}
See also:
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论