Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Is it possible for coroutines to set struct values and call methods? #7

Open
veniamin-ilmer opened this issue Sep 13, 2022 · 1 comment

Comments

@veniamin-ilmer
Copy link

I have code which failed with generators, but I am hoping to work with coroutines. Please bear with me as I am coming from the imperative programming world.

use corosensei::{Coroutine, CoroutineResult, Yielder};

fn main() {
  let mut example = Example { data1: 0, data2: 0 };

  let mut coroutine = example.continue_run();

  let mut input = 0;
  loop {
    match coroutine.resume(input) {
      CoroutineResult::Yield(number) => {
        //Test mutable methods could be called during a yield.
        input = example.increment(number);
      }
      CoroutineResult::Return(()) => {
        break;
      }
    }
  }
}

struct Example {
  data1: usize,
  data2: usize,
}

impl Example {
  fn continue_run(&mut self) -> Coroutine<usize, usize, ()> {
    Coroutine::new(|yielder, _| {
      //Test mutable methods can be called within a coroutine.
      self.test_method(yielder);
    })
  }

  fn test_method(&mut self, yielder: &Yielder<usize, usize>) {
    let input = yielder.suspend(123);
    println!("Returned {} after yielding", input);
    //Test struct data can be mutated within a coroutine.
    self.data1 = input;
  }

  fn increment(&mut self, number: usize) -> usize {
    //Test struct data can be mutated during a yield.
    self.data2 = number;
    number+1
  }
}

Is there a way for me to get this code to work? Or are coroutines and mutable methods not compatible with each other?

Thank you!

@Amanieu
Copy link
Owner

Amanieu commented Nov 2, 2022

The problem here is ownership of the object. You need to either place Example entirely inside the coroutine, or at least split it into 2 structs: one outer struct which contains the coroutine, and an inner struct that contains the data which is contained within the coroutine.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants