fixed minor differences between 'compiled' generators and the example used. Added bonus section to prove it works
This commit is contained in:
@@ -221,7 +221,6 @@ Instead of discussing it in theory, let's look at some code.
|
||||
let mut gen = move || {
|
||||
let to_borrow = String::from("Hello");
|
||||
let borrowed = &to_borrow;
|
||||
println!("{}", borrowed);
|
||||
yield borrowed.len();
|
||||
println!("{} world!", borrowed);
|
||||
};
|
||||
@@ -513,8 +512,52 @@ Hopefully, after this you'll have an idea of what happens when you use the
|
||||
`yield` or `await` keywords inside an async function, and why we need `Pin` if
|
||||
we want to be able to safely borrow across `yield/await` points.
|
||||
|
||||
|
||||
## Bonus
|
||||
|
||||
Thanks to [PR#45337][pr45337] you can actually run code like the one we display here in Rust
|
||||
today using the `static` keyword on nightly. Try it for yourself:
|
||||
|
||||
|
||||
```rust
|
||||
#![feature(generators, generator_trait)]
|
||||
use std::ops::{Generator, GeneratorState};
|
||||
|
||||
|
||||
pub fn main() {
|
||||
let gen1 = static || {
|
||||
let to_borrow = String::from("Hello");
|
||||
let borrowed = &to_borrow;
|
||||
yield borrowed.len();
|
||||
println!("{} world!", borrowed);
|
||||
};
|
||||
|
||||
let gen2 = static || {
|
||||
let to_borrow = String::from("Hello");
|
||||
let borrowed = &to_borrow;
|
||||
yield borrowed.len();
|
||||
println!("{} world!", borrowed);
|
||||
};
|
||||
|
||||
let mut pinned1 = Box::pin(gen1);
|
||||
let mut pinned2 = Box::pin(gen2);
|
||||
|
||||
if let GeneratorState::Yielded(n) = pinned1.as_mut().resume() {
|
||||
println!("Gen1 got value {}", n);
|
||||
}
|
||||
|
||||
if let GeneratorState::Yielded(n) = pinned2.as_mut().resume() {
|
||||
println!("Gen2 got value {}", n);
|
||||
};
|
||||
|
||||
let _ = pinned1.as_mut().resume();
|
||||
let _ = pinned2.as_mut().resume();
|
||||
}
|
||||
```
|
||||
|
||||
[rfc2033]: https://github.com/rust-lang/rfcs/blob/master/text/2033-experimental-coroutines.md
|
||||
[greenthreads]: https://cfsamson.gitbook.io/green-threads-explained-in-200-lines-of-rust/
|
||||
[rfc1823]: https://github.com/rust-lang/rfcs/pull/1823
|
||||
[rfc1832]: https://github.com/rust-lang/rfcs/pull/1832
|
||||
[optimizing-await]: https://tmandry.gitlab.io/blog/posts/optimizing-await-1/
|
||||
[optimizing-await]: https://tmandry.gitlab.io/blog/posts/optimizing-await-1/
|
||||
[pr45337]: https://github.com/rust-lang/rust/pull/45337/files
|
||||
Reference in New Issue
Block a user