根据Rust .try_iter()的Receiver
端的std::mpsc::channel
方法的文档,我知道此迭代器要么产生“ None”:
就我而言,我想peek
进入频道,而不会阻塞,以便确定是否:
问题是,如果我..
peek
..我只能区分两种情况。
我如何窥视通道的match my_receiver.try_iter().peekable().peek() {
Some(data) => {/* there is data */}
None => {/* there is no data, but there may be later.. or maybe not, because the channel has maybe hung up, I can't tell! */}
}
端并在可能的结果之间进行区分,而不会阻塞或消耗某些数据呢?
match my_receiver.try_recv() {
Ok(data) => {/* handle data */}
Err(TryRecvError::Disconnected) => {/* handle sender disconnected */}
Err(TryRecvError::Empty) => {/* handle no data available yet */}
}
方法返回一个丢弃try_iter()
值的迭代器,因此您无法区分大小写。
您可以创建自己的迭代器,该迭代器在Error
上进行迭代,而不是丢弃错误值:
Result
然后您将能够获得一个可窥视的迭代器,该迭代器将返回三个可能的条件:
pub struct TryIterResult<'a, T: 'a> {
rx: &'a Receiver<T>,
}
pub fn try_iter_result<'a, T>(rx: &'a Receiver<T>) -> TryIterResult<'a, T> {
TryIterResult { rx: &rx }
}
impl<'a, T> Iterator for TryIterResult<'a, T> {
type Item = Result<T, TryRecvError>;
fn next(&mut self) -> Option<Result<T, TryRecvError>> {
match self.rx.try_recv() {
Ok(data) => Some(Ok(data)),
Err(TryRecvError::Empty) => Some(Err(TryRecvError::Empty)),
Err(TryRecvError::Disconnected) => None
}
}
}