liveBook · Manning

Yield

As explained in Idiomatic Rust

A yield statement suspends a coroutine and optionally supplies a value to its caller.

A `yield` statement suspends a coroutine and optionally sends a value to its caller. Resuming continues execution after the yield; returning completes the coroutine, which cannot be resumed again. Omitting the yield value is equivalent to yielding `()`. section 8.2

Listing 8.6 A basic coroutine in Rust
#![feature(coroutines,               #1
           coroutine_trait,      #1   
           stmt_expr_attributes)]   #1

use core::f64::consts::PI;
use std::ops::{Coroutine, CoroutineState};
use std::pin::Pin;


fn main() {
    let mut yield_pi = #[coroutine]      #2
    || {                                     #3
        yield PI;                          #4
        "Coroutine complete!"     #5
    };

    loop {
        match Pin::new(&mut yield_pi).resume(()) {     #6
            CoroutineState::Yielded(val) => {      #7
                dbg!(&val);
            }
            CoroutineState::Complete(val) => {     #8
                dbg!(&val);
                break;
            }
        }
    }
}

See a coroutine closure yield π on its first resume, then return a completion string on its second. section 8.2

How Idiomatic Rust covers it

How deep it goes
Traces yielding through resume calls and coroutine states, with a basic example; defers more complex scenarios.
Examples
Demonstrates yielding π before returning a string, and yielding numbered file lines for an iterator.
What you can do after
Build a coroutine closure that yields values on resume and returns a completion value.
How it connects
Connects coroutines with iterators, async/await, context switching, and multiplexing.

Also explained in

Compare how 10 books explain yield →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Idiomatic Rust. The section links point to the parts of the book it draws on.