Rust 中的惰性序列生成 [英] Lazy sequence generation in Rust

查看:13
本文介绍了Rust 中的惰性序列生成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何创建其他语言称为惰性序列或生成器"函数的函数?

How can I create what other languages call a lazy sequence or a "generator" function?

在 Python 中,我可以使用 yield 如下例(来自 Python 的文档)来延迟生成一个序列,该序列可以不使用中间列表的内存的方式迭代:

In Python, I can use yield as in the following example (from Python's docs) to lazily generate a sequence that is iterable in a way that does not use the memory of an intermediary list:

# a generator that yields items instead of returning a list
def firstn(n):
    num = 0
    while num < n:
        yield num
        num += 1

sum_of_first_n = sum(firstn(1000000))

如何在 Rust 中做类似的事情?

How can I do something similar in Rust?

推荐答案

Rust 1.0 没有生成器功能,所以你必须手动使用 显式迭代器.

Rust 1.0 does not have generator functions, so you'd have to do it manually with explicit iterators.

首先,将您的 Python 示例重写为具有 next() 方法的类,因为它更接近您可能在 Rust 中获得的模型.然后你可以在 Rust 中用一个实现 Iterator trait 的结构重写它.

First, rewrite your Python example as a class with a next() method, since that is closer to the model you're likely to get in Rust. Then you can rewrite it in Rust with a struct that implements the Iterator trait.

您也可以使用返回闭包的函数来实现类似的结果,但我认为不可能实现 Iterator 特性(因为它会需要被调用以生成新结果).

You might also be able to use a function that returns a closure to achieve a similar result, but I don't think it would be possible to have that implement the Iterator trait (since it would require being called to generate a new result).

这篇关于Rust 中的惰性序列生成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆