use std::mem::{self, ManuallyDrop};
/// single producer multi consumer
#[tokio::main]
async fn main() {
use tokio::sync::watch;
use tokio::time::{Duration, sleep};
let (tx, _rx) = watch::channel("hello");
let mut rx2 = tx.subscribe();
tokio::spawn(async move {
loop {
let res = rx2.has_changed();
if res.is_err() {
break;
}
if !res.ok().unwrap_or_else(|| true ) {
continue;
}
println!("{}! ", *rx2.borrow_and_update());
}
});
sleep(Duration::from_millis(1000)).await;
for i in 0..10 {
let val = format!("World {}!", i);
tx.send(val.as_str()).unwrap();
}
sleep(Duration::from_millis(1000)).await;
}
这是代码,我面临一个问题。
该论证要求借用
val
来代替 'static
由于这一行,通道的元素类型被推断为
&str
:
let (tx, _rx) = watch::channel("hello");
然后,您发送
val.as_str()
,它返回一个借用于 &str
的 val
,但是 val
将在循环迭代结束时被销毁。
只需发送自有值 (
String
) 而不是借用的值。您可以通过发送 val
而不是 val.as_str()
来完成此操作。您还必须发送 "hello".to_owned()
而不是 "hello"
才能使类型匹配。