Pattern matching
Recall that the select!
macro branch syntax was defined as:
<pattern> = <async expression> => <handler>,
So far, we have only used variable bindings for <pattern>
. However, any Rust pattern can be used. For example, say we are receiving from multiple MPSC channels, we might do something like this:
use tokio::sync::mpsc;
#[tokio::main]
async fn main() {
let (mut tx1, mut rx1) = mpsc::channel(128);
let (mut tx2, mut rx2) = mpsc::channel(128);
tokio::spawn(async move {
// Do something w/ `tx1` and `tx2`
});
tokio::select! {
Some(v) = rx1.recv() => {
println!("Got {:?} from rx1", v);
}
Some(v) = rx2.recv() => {
println!("Got {:?} from rx2", v);
}
else => {
println!("Both channels closed");
}
}
}
In this example, the select!
expression waits on receiving a value from rx1
and rx2
. If a channel closes, recv()
returns None
. This does not match the pattern and the branch is disabled. The select!
expression will continue waiting on the remaining branches.
Notice that this select!
expression includes an else
branch. The select!
expression must evaluate to a value. When using pattern matching, it is possible that none of the branches match their associated patterns. If this happens, the else
branch is evaluated.