【发布时间】: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<Item = i32>、impl Iterator 等,但我要么得到错误,要么得到编译器恐慌,要么两者兼而有之。对不起,如果这是一个愚蠢的问题;我只使用 Rust 大约三个月。但不知何故,感觉这应该更简单。
所以我的问题是:返回使用yield 关键字生成的迭代器的函数的正确语法是什么?我查看了Rust Documentation 和The Book,但没有发现任何有用的信息。
【问题讨论】:
-
错误提示 “yield 语法是实验性的” - 您是否正在寻找一个答案来演示如何以实验形式使用此语法,或者您是否对惯用的解决方案更感兴趣你想要达到什么目的?
-
@kmdreko 我知道语法是实验性的,但我认为它比错误消息中明显的要远。如果
yield关键字比任何其他解决方案都简单,我想使用它。如果不是,那么欢迎使用任何其他解决方案。我的最终目标是能够返回由迭代创建的迭代器。