Jamie McCrindle
Jamie McCrindle

Reputation: 9214

How do I use Rust's std::iter::iterate method

The iter package has an iterate method std::iter::iterate but I can't find an example of how to use it anywhere. Ideally I'd like to see how to return the result of std::iter::iterate as iterator for example, this method in ruby that returns whole numbers:

def whole_numbers()
    iterate(0) do |current|
        current + 1
    end
end

Upvotes: 0

Views: 195

Answers (1)

Levans
Levans

Reputation: 15002

iterate(..) returns the iterator itself, you can then use it directly, like that:

let mut it = std::iter::iterate(0u, |x| x+1);

for i in it {
    println!("{}", i);
}

If you need to pass this iterator around, you just need to mimic the return type of iterate(), which is :

pub fn iterate<'a, T: Clone>(seed: T, f: |T|: 'a -> T) -> Iterate<'a, T>

for example:

use std::iter::{Iterate, iterate};

pub fn create_counter() -> Iterate<'static, uint> {
    return iterate(0u, |x| x+1);
}

Upvotes: 2

Related Questions