Include branch by condition in tokio::select macro

What is a way to do something like:

let (tx1, rx1) = mpsc::channel();
let (tx2, rx2) = mpsc::channel();

let use_rx1 = true;

select! {
    if use_rx1 {
        msg = rx1.recv() => {...}
    } else {
        msg = rx2.recv() => {...}
    }
}

Like this maybe?

use tokio::select;
use tokio::sync::mpsc;

#[tokio::main]
async fn main() {
    let (tx1, mut rx1) = mpsc::channel::<()>(1);
    let (tx2, mut rx2) = mpsc::channel::<()>(1);

    let use_rx1 = true;

    select! {
        msg = if use_rx1 { rx1.recv() } else { rx2.recv() } => {}
    }
}

Playground.

Another option maybe not as pretty

tokio::select! { // the futures::select doesn't have guards
    msg = rx1, if use_rx1 => {}
    msg = rx2 => {}
}
2 Likes

This will only work if channels hold values of same type, which is not always the case.
Also, using select macro is not a necessity. I think this can be achived by manual select implementation, but this will require reimplementing random branch selection which select does. This seems like a lot of effort just to include a branch.