Trait in prelude auto-imported

Iterator

trait Iterator<I>
Source: compiler/src/builtin_docs/prelude.hy

A source of values that for loops pull from one at a time.

Implementations define the associated type Item (the element type) and next, which returns Some(item) for each value and None when the sequence is exhausted. for x in e first converts e with IntoIterator, then calls next until it returns None. Arrays, Vec, homogeneous tuples, coroutines and numeric ranges are iterable without an impl; a record is not iterable (use collections::map::HashMap for keys to iterate).

Associated types#

  • type Item

Required methods#

NameDescription
nextReturns the next value, or None when the iterator is exhausted.

Examples#

use tests::assert;
class Countdown {
    pub n: int,
}

impl Iterator for Countdown {
    type Item = int;
    pub fn next(Countdown c) -> Option<int> {
        if c.n == 0 {
            return Option::None;
        }
        c.n = c.n - 1;
        return Option::Some(c.n + 1);
    }
}

impl IntoIterator for Countdown {
    type Item = int;
    type IntoIter = Countdown;
    pub fn into_iter(Countdown c) -> Countdown {
        return c;
    }
}

fn main() {
    let seen = 0;
    for x in new Countdown(3) {
        seen = seen * 10 + x;
    }
    assert!(seen == 321);
}

See also#

↑ ↓ navigate ↵ open