liveBook · Manning

Coroutine trait

As explained in Idiomatic Rust

The Rust Coroutine trait defines the interface and associated behavior for resuming a coroutine and observing its yielded or completed result.

The Coroutine trait defines how to resume a coroutine and distinguish a yielded value from its final return. The compiler implements it for coroutine closures; understanding the interface helps with more complex uses. section 8.2

Listing 8.5 std::ops::Coroutine trait definition from Rust standard library
pub trait Coroutine<R = ()> {     #1
    type Yield;                     #2
    type Return;                   #3

    // Required method
    fn resume(
        self: Pin<&mut Self>,      #4
        arg: R
    ) -> CoroutineState<Self::Yield, Self::Return>;
}

The signature exposes the input type, yielded and returned types, and pinned resume method. section 8.2

Yield, then complete

A coroutine closure yields pi on its first resume and returns a string on its second. Matching CoroutineState distinguishes the two outcomes. section 8.2

How Idiomatic Rust covers it

How deep it goes
Specifies associated Yield and Return types and pinned resume, and describes state transitions without requiring manual trait implementation.
Examples
Uses a coroutine that yields pi before returning a string, and a line-reading coroutine adapted as an iterator.
What you can do after
Understand how to resume compiler-generated coroutines and distinguish yielded values from their final return.
How it connects
Connects coroutines with async/await, iterators, and state machines.

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.