Create generator without nested closure? 创建没有嵌套闭包的生成器?

huangapple go评论62阅读模式
英文:

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) -&gt; impl Generator&lt;...&gt; {
  || {
    for x in 0..i {
      yield x;
    }
  }
}

But is there syntax to do something like the following without macros?

fn do_thing(i: i32) -&gt; impl Generator&lt;...&gt; {
  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.

huangapple
  • 本文由 发表于 2023年5月24日 21:54:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/76324301.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定