TrySendError Matching On Bounded Sends

try_send refuses immediately when a bounded channel is full and returns TrySendError::Full, and after the receiver drops it reports Disconnected.

RustResilience

Code

rustsnippet
25 lines
use std::sync::mpsc::{sync_channel, TrySendError};

fn main() {
    let (tx, rx) = sync_channel::<i32>(2); // bounded capacity: 2
    let mut queued = 0;

    tx.send(1).unwrap();
    queued += 1;
    tx.try_send(2).expect("buffered slot free");
    queued += 1;
    println!("queued: {queued}");

    // buffer full: try_send refuses instead of blocking, value returned as-is
    match tx.try_send(3) {
        Ok(()) => println!("accepted"),
        Err(TrySendError::Full(_)) => println!("full at {queued}: try_send refused"),
        Err(TrySendError::Disconnected(_)) => println!("receiver gone"),
    }

    drop(rx);
    match tx.try_send(4) {
        Ok(()) => println!("accepted after drop"),
        Err(TrySendError::Disconnected(_)) => println!("disconnected after receiver dropped"),
    }
}

What the demo refuses

A sync_channel with capacity 2 takes two sends, one blocking send for the first slot and try_send for the second, before the printed queued: 2. The third try_send meets a full buffer and returns Err(TrySendError::Full), refusing instead of blocking; the match prints full at 2.

After drop(rx), the channel is disconnected: try_send now reports TrySendError::Disconnected, printed as disconnected after receiver dropped. The value inside each error stays untouched, which is how callers recover the refused item.

Points worth noting

  • try_send never waits; full or disconnected, it returns at once.
  • Both error variants carry the value that was not delivered.

Interactive Tools for This Topic

FAQ

What happens to a value refused by try_send?
It comes back inside the error: the Full and Disconnected variants wrap the original value, so the refused 3 and 4 in the demo are recoverable from the match arms.