2

Is it possible to clone a variable of type std::ops::Generator? There is a generator, I want to create a new instance, with a clean stack, there is no clone() method. I tried inside Box and inside Pin, but it does not clone!

#![feature(generators, generator_trait)]

fn main() {
    let gen = move || yield ();

    let gen1 = gen.clone();

    let gen = Box::new(move || yield ());
    let gen1 = gen.clone();

    let gen = Box::pin(move || yield ());
    let gen1 = gen.clone();
}
error[E0599]: no method named `clone` found for type `[generator@src/main.rs:4:15: 4:31 _]` in the current scope
 --> src/main.rs:6:20
  |
6 |     let gen1 = gen.clone();
  |                    ^^^^^

As I understand it, closures can be cloned; what is wrong with generators?

The only workaround I've found is to return the generator from some function (then it will be new every time), but this is syntactically inconvenient for me.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
epishman
  • 65
  • 4

1 Answers1

2

No, it is not possible to clone a generator.

The current workaround is to construct a new generator every time you need to reset it.

a variable of type std::ops::Generator

These are not variables of that type any more than || foo() is a variable of type Fn(). Generator is a trait and dyn Generator is a type. Your gen variables are anonymous types that implement the trait Generator.

See also:

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366