如何在 Rust 中使用 Yield 关键字?

Syl*_*act 5 iterator yield rust

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

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

for i in func():
    print(i)
Run Code Online (Sandbox Code Playgroud)

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

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

fn main() {
    for i in func() {
        println!("{}", i);
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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
Run Code Online (Sandbox Code Playgroud)

根据错误消息中的帮助,我一直在尝试使用不同的返回类型,例如dyn Iterator<Item = i32>、等,并且我要么收到错误,要么出现编译器恐慌,或者两者兼而有之。impl Iterator抱歉,如果这是一个愚蠢的问题;我只使用 Rust 大约三个月。但不知怎的,感觉这应该更简单。

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

Net*_*ave 9

迭代器需要实现Iterator特征。Rust 不使用生成器yield关键字(目前为),因此您不能使用它。您的代码的直接翻译将是:Rust 1.57

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

fn main() {
    for i in func() {
        println!("{}", i);
    }
}
Run Code Online (Sandbox Code Playgroud)

(0..100)一个Range实现的对象Iterator

参考

  1. 迭代器
  2. 发电机(不稳定)
  3. Walkdir(解决类似问题)