← 中文资源

简体中文版本

TrySendError 匹配有界发送

有界 channel 用 try_send 非阻塞投递:缓冲满时立即返回 TrySendError::Full 且值原样退回;接收端 drop 后再发则报 Disconnected。

阅读英文原文

实现说明

TrySendError 匹配有界发送可以归结为函数 main。 通过 match 做模式匹配,值的每种形态都必须被处理。

使用要点

  • 演示输出是带标签的(queued:、accepted、full at),每个操作都会留下自己的一行标注。

常见问题

运行「TrySendError 匹配有界发送」会打印什么?

运行文件本身,queued:、accepted、full at 这些前缀各对应一段演示逻辑。

核心语句

match tx.try_send(3) {
    Ok(()) => println!("accepted"),
    Err(TrySendError::Full(_)) => println!("full at {queued}: try_send refused"),
    Err(TrySendError::Disconnected(_)) => println!("receiver gone"),
}
match tx.try_send(4) {
    Ok(()) => println!("accepted after drop"),
    Err(TrySendError::Disconnected(_)) => println!("disconnected after receiver dropped"),
}
tx.send(1).unwrap();

代码示例

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"),
    }
}