liveBook · Manning

Try_join macro

As explained in Learn Rust in a Month of Lunches

The try_join! macro concurrently joins futures and returns an error as soon as one of them fails.

The try_join! macro polls several futures concurrently, returns their successful results as a tuple, and produces an Err when one future fails. section 19.3.4

Joining successful and failed futures

Three wait_then_u8 futures demonstrate both outcomes: one failed future produces Err("Oops, didn't work"), while three successful futures produce Ok((1, 2, 3)). section 19.3.4

use tokio::try_join;
 
async fn wait_then_u8(num: u8, worked: bool) -> Result<u8, &'static str> {
    if worked {
        Ok(num)
    } else {
        Err("Oops, didn't work")
    }
}
 
#[tokio::main]
async fn main() {
    let failed_join = try_join!(
        wait_then_u8(1, true),
        wait_then_u8(2, false),
        wait_then_u8(3, true)
    );
 
    let successful_join = try_join!(
        wait_then_u8(1, true),
        wait_then_u8(2, true),
        wait_then_u8(3, true)
    );
 
    println!("{failed_join:?}");
    println!("{successful_join:?}");
}

Use the focused Tokio example to compare failed and successful try_join! calls. section 19.3.4

How Learn Rust in a Month of Lunches covers it

How deep it goes
Defines the macro through a compact example and printed outcomes without exploring polling internals or error propagation details.
Examples
Demonstrates wait_then_u8 futures with one failure and with three successful results.
What it assumes
Assumes basic familiarity with async futures and Result values while keeping the macro explanation example-driven.
What you can do after
Apply it via Tokio to join fallible futures and inspect Err or tuple-valued Ok results.
How it connects
Connects asynchronous futures, Result values, Tokio, and concurrent joining.

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