我有一个具有可枚举值集的类型:
struct MyType(u32);
我可以在一组值上定义一个迭代器:
struct MyTypeIter {
m: MyType,
}
impl Iterator for MyTypeIter {
type Item = MyType;
fn next(&mut self) -> Option<Self::Item> {
if (self.m).0 < 0xffffffff {
(self.m).0 += 1;
Some(MyType((self.m).0 - 1))
} else {
None
}
}
}
impl MyTypeIter {
fn new() -> MyTypeIter {
MyTypeIter { m: MyType(0) }
}
}
这真的是规范的方式吗?如果我们有多个自然顺序(比如迭代 lex/colex 顺序中的排列或组合)怎么办?
最佳答案
What if we have several natural orders (like iterating over permutations or combinations in lex/colex order)?
针对不同的迭代顺序实现不同的迭代器类型。除了 MyTypeIter
,您还可以拥有多个迭代器类型,例如 MyTypePermutationIter
和 MyTypeCombinationIter
。
标准库在很多地方都采用了这种方法。以字符串切片类型 str
为例.您可以自然地遍历字符串的字节、UTF-8 字符或行(举几个例子)。为此,str
公开了不同的方法:
关于iterator - 这是迭代一组值的规范方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50720654/