【问题标题】:How do I use the yield keyword in Rust? [duplicate]如何在 Rust 中使用 yield 关键字? [复制]
【发布时间】:2022-01-10 01:50:00
【问题描述】:

我正在尝试创建一个函数,该函数将返回目录中所有文件的迭代器,包括子目录中的所有文件。由于我不知道包含所有文件路径的数组的大小,我认为让函数返回迭代器而不是数组会更容易。在 Python 中很简单:

def func():
    for i in range(0, 100):
        yield i

for i in func():
    print(i)

但是当我尝试在 Rust 中做类似的事情时,我会遇到编译器错误和/或编译器恐慌。在这里,我尝试了一些接近 Python 的基本语法:

fn func() -> Iterator {
    for i in 0..100 {
        yield i;
    }
}

fn main() {
    for i in func() {
        println!("{}", i);
    }
}

但是当我编译它时,它导致了两个错误和一个警告:

error[E0658]: yield syntax is experimental
 --> src/main.rs:3:9
  |
3 |         yield i;
  |         ^^^^^^^
  |
  = note: see issue #43122 <https://github.com/rust-lang/rust/issues/43122> for more information

warning: trait objects without an explicit `dyn` are deprecated
 --> src/main.rs:1:14
  |
1 | fn func() -> Iterator {
  |              ^^^^^^^^ help: use `dyn`: `dyn Iterator`
  |
  = note: `#[warn(bare_trait_objects)]` on by default
  = warning: this is accepted in the current edition (Rust 2018) but is a hard error in Rust 2021!
  = note: for more information, see issue #80165 <https://github.com/rust-lang/rust/issues/80165>

error[E0191]: the value of the associated type `Item` (from trait `Iterator`) must be specified
 --> src/main.rs:1:14
  |
1 | fn func() -> Iterator {
  |              ^^^^^^^^ help: specify the associated type: `Iterator<Item = Type>`

Some errors have detailed explanations: E0191, E0658.
For more information about an error, try `rustc --explain E0191`.
warning: `problem` (bin "problem") generated 1 warning
error: could not compile `problem` due to 2 previous errors; 1 warning emitted

根据错误消息中的帮助,我一直在尝试使用不同的返回类型,例如dyn Iterator&lt;Item = i32&gt;impl Iterator 等,但我要么得到错误,要么得到编译器恐慌,要么两者兼而有之。对不起,如果这是一个愚蠢的问题;我只使用 Rust 大约三个月。但不知何故,感觉这应该更简单。

所以我的问题是:返回使用yield 关键字生成的迭代器的函数的正确语法是什么?我查看了Rust DocumentationThe Book,但没有发现任何有用的信息。

【问题讨论】:

  • 错误提示 “yield 语法是实验性的” - 您是否正在寻找一个答案来演示如何以实验形式使用此语法,或者您是否对惯用的解决方案更感兴趣你想要达到什么目的?
  • @kmdreko 我知道语法是实验性的,但我认为它比错误消息中明显的要远。如果yield 关键字比任何其他解决方案都简单,我想使用它。如果不是,那么欢迎使用任何其他解决方案。我的最终目标是能够返回由迭代创建的迭代器。

标签: rust iterator yield


【解决方案1】:

迭代器需要实现Iterator trait。 Rust 没有为 generators 使用 yield 关键字(目前是 Rust 1.57),所以你不能使用它。 您的代码的直接翻译是:

fn func() -> impl Iterator<Item=u32> {
    0..100u32
}

fn main() {
    for i in func() {
        println!("{}", i);
    }
}

(0..100) 是一个实现IteratorRange 对象

参考文献

  1. Iterator
  2. Generators (Unstable)
  3. Walkdir (solving a similar problem)

【讨论】:

  • 好吧,看来 Walkdir 解决了这个问题。这个问题真的不是我想要的,但我不能删除它。我想我会回滚刚才所做的编辑,并保持原样。感谢您的推荐!完成回滚后,我会立即接受您的回答。
猜你喜欢
  • 2020-11-28
  • 2012-07-01
  • 2011-12-25
  • 1970-01-01
  • 2020-10-02
  • 2011-06-08
  • 2018-01-20
  • 2019-07-06
  • 1970-01-01
相关资源
最近更新 更多