这似乎是借用检查器的误报,可能与所讨论的已知局限性密切相关
here
.
如果你使用
watch::Receiver::wait_for
,它编译得很好:
use std::ops::Deref;
use tokio::sync::watch;
pub struct WatchSomeRef<'a, T>(watch::Ref<'a, Option<T>>);
impl<T> Deref for WatchSomeRef<'_, T> {
type Target = T;
fn deref(&self) -> &Self::Target {
self.0.as_ref().unwrap()
}
}
pub async fn recv_some<T>(
rx: &mut watch::Receiver<Option<T>>,
) -> Result<WatchSomeRef<T>, watch::error::RecvError> {
let value = rx.wait_for(|val| val.is_some()).await?;
Ok(WatchSomeRef(value))
}
或者更紧凑的版本:
pub async fn recv_some<T>(
rx: &mut watch::Receiver<Option<T>>,
) -> Result<WatchSomeRef<T>, watch::error::RecvError> {
rx.wait_for(Option::is_some).await.map(WatchSomeRef)
}