You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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!
The text was updated successfully, but these errors were encountered:
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.
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.
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!
The text was updated successfully, but these errors were encountered: