简体   繁体   English

我如何使用Rust的std :: iter :: iterate方法

[英]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. iter包有一个迭代方法std :: iter :: iterate,但是我找不到在任何地方使用它的示例。 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: 理想情况下,我想看看如何将std :: iter :: iterate的结果返回为迭代器,例如,该方法在ruby中返回整数:

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

iterate(..) returns the iterator itself, you can then use it directly, like that: iterate(..)返回迭代器本身,然后可以直接使用它,如下所示:

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 : 如果您需要传递此迭代器,则只需模仿iterate()的返回类型,即:

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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM