Lazy sequence generation in Rust

前端 未结 4 2063
梦毁少年i
梦毁少年i 2020-12-05 04:20

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

In Python, I can use yield as in the following example (from Pyt

4条回答
  •  我在风中等你
    2020-12-05 05:03

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

    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.

    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).

提交回复
热议问题