Select in Rust
Rust’s select!
macro allows you to wait on multiple channel operations. Combining threads and channels with select!
is a powerful feature of Rust.
To run this program, you would typically save it as select_example.rs
and use cargo run
if it’s part of a Cargo project, or rustc select_example.rs
followed by ./select_example
if compiling directly.
The output would be:
Note that the total execution time is only ~2 seconds since both the 1 and 2 second sleep
operations execute concurrently.
In Rust, we use thread::spawn
to create new threads, which is similar to goroutines in concept. The mpsc::channel()
function creates a multiple producer, single consumer channel, which we use for communication between threads. The select!
macro in Rust provides similar functionality to Go’s select
statement, allowing us to wait on multiple channel operations simultaneously.