私は定数(呼び出し時に)引数xのシーケンスx^2、x^2 + x、x^2 + 2x、x^2 + 3x ...を生成するIteratorを実装しようとしています。錆。どのように後継者が用語のインデックスに依存するIteratorを実装していますか?
私が理解しているように、実装のどの時点でも作業しなければならないのは、self.curr
とself.next
です。シーケンスは、シーケンス内のアイテムのインデックスに依存するようです。
struct SquareMultiple {
// generates the sequence j = i^2, i^2+i, i^2+2i, i^2+3i, ...,
curr: i64,
next: i64,
}
// Implement `Iterator` for `SquareMultiple`.
// The `Iterator` trait only requires a method to be defined for the `next`
// element.
impl Iterator for SquareMultiple {
type Item = i64;
// Here, we define the sequence using `.curr` and `.next`.
// The return type is `Option<T>`:
// * When the `Iterator` is finished, `None` is returned.
// * Otherwise, the next value is wrapped in `Some` and returned.
fn next(&mut self) -> Option<I64> {
// FIXME: What to do here?
let new_next = self.curr + self.next;
self.curr = self.next;
self.next = new_next;
// Since there's no endpoint to a SquareMultiple sequence, the
// `Iterator` will never return `None`, and `Some` is always returned.
Some(self.curr)
}
}
// Returns a SquareMultiple sequence generator
fn squareseq() -> SquareMultiple {
SquareMultiple { curr: 1, next: 2 }
}
私もindex
属性を持つ構造体に過負荷をかけると考えられ、それがこのパターンの乱用のように何とかようです。
これについてはどのような方法がありますか?
を/iter/trait.Iterator.html#method.nth)メソッドを使用します。 – malbarbo