liveBook · Manning

Select macro

As explained in Learn Rust in a Month of Lunches

The select! macro concurrently polls multiple futures and executes the branch corresponding to the first future that completes.

The select! macro polls multiple futures concurrently and runs the branch for the first future to complete. Each branch names its future, uses =>, and handles that future’s output. section 19.3.4

Use select! when:

  • Several asynchronous operations can finish first, and only the earliest result matters. section 19.3.4
  • Different futures return different types; convert their outputs inside branches so every branch produces a compatible result. section 19.3.4
  • A timeout should compete with the main operations; an unnamed future can return a timeout message. section 19.3.4

Racing operations against a timeout

select!( first = sleep_then_string(10) => first, second = sleep_then_string(11) => second, third = sleep_then_num(12) => format!("Slept for {third} millis!"), _ = sleep(Duration::from_millis(100)) => format!("Timed out after 100 millis!") ); The first completed future determines num. Because the waits are close together, changing their durations can change the output. section 19.3.4

How Learn Rust in a Month of Lunches covers it

How deep it goes
Defines branch syntax and demonstrates mixed outputs, but stops short of implementation internals or detailed cancellation behavior.
Examples
Uses sleeping string and number futures plus a 100-millisecond timeout to demonstrate varying completion order.
What it assumes
Assumes familiarity with async functions, futures, .await, and concurrent polling; explains select! branch syntax directly.
What you can do after
Apply it via Tokio to race futures, normalize branch outputs, and implement a simple asynchronous timeout.
How it connects
Connects select! with futures, async functions, .await, join!, try_join!, and external asynchronous crates.

Related concepts

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.