liveBook · Manning

Crossterm

As explained in Learn Rust in a Month of Lunches

Crossterm is a Rust cross-platform terminal I/O library for handling events such as keyboard input, mouse input, and terminal resizing.

Crossterm is a Rust crate for detecting and reacting to terminal input as it happens. It can observe keyboard input, mouse input, and screen resizing while supporting both Unix/Linux and Windows terminals. section 23.2.1

Crossterm represents terminal interaction through events:

  • read() waits until an event occurs, making it useful when the program only needs to react to input. section 23.2.1
  • poll() checks for an event for a chosen Duration, including zero duration, so an application can update continuously without waiting for a key. section 23.4.2
  • Keyboard events expose the character, modifier keys such as Shift, and whether the key was pressed or released. section 23.2.1

A minimal event loop

Add crossterm = "0.26.1" to Cargo.toml, import crossterm::event::read, and call read().unwrap() inside a loop. Printing each result reveals the events generated as keys are pressed and released. A stopwatch can instead use poll(Duration::from_millis(0)) so it redraws while still checking for input. section 23.2.1 section 23.4.2

use crossterm::event::read;
 
fn main() {
    loop {
        println!("{:?}", read().unwrap());
    }
}

Runnable minimal loop for inspecting Crossterm keyboard events. section 23.2.1

How Learn Rust in a Month of Lunches covers it

How deep it goes
Explains dependency setup, event fields, blocking versus timed polling, and integration with a redrawing interface without covering library internals.
Examples
Uses a printed keyboard-event loop and a stopwatch that polls input while continuously updating its display.
What it assumes
Assumes basic Rust and Cargo familiarity, while demonstrating dependency configuration and event-loop usage directly.
What you can do after
Build interactive terminal programs that inspect keyboard events and keep updating while input is absent.
How it connects
Connects keyboard events, event loops, terminal interfaces, and ratatui widgets.

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.