英文:
Create generator without nested closure?
问题
是否可以创建一个生成器而不使用嵌套闭包?我知道目前可以通过类似于以下伪Rust的方式创建生成器:
fn do_thing(i: i32) -> impl Generator<...> {
|| {
for x in 0..i {
yield x;
}
}
}
但是否有类似下面的语法可以做到,而不需要使用宏?
fn do_thing(i: i32) -> impl Generator<...> {
for x in 0..i {
yield x;
}
}
这似乎是一种奇怪的设计选择,因为异步函数不需要一个中间闭包/异步块,而这些是在底层使用生成器实现的。
英文:
Is it possible to create a generator without using a nested closure? I know that currently, you can create a generator via something similar to this pseudo-rust:
fn do_thing(i: i32) -> impl Generator<...> {
|| {
for x in 0..i {
yield x;
}
}
}
But is there syntax to do something like the following without macros?
fn do_thing(i: i32) -> impl Generator<...> {
for x in 0..i {
yield x;
}
}
This seems like an odd design choice since async functions don't need an intermediary closure / async block, and those are implemented with generators under the hood.
答案1
得分: 2
生成器是一个不够成熟的功能。有许多未解决的问题,其中之一是定义生成器函数的能力,就像您想要的那样。
目前,使用闭包是一种可行的方法。
英文:
Generators are a half-baked feature. There are many unresolved questions with them, and one of them is ability to define generator functions like you want.
For now, using a closure is the way to go.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论