需要帮助解决观看频道 tokio 中的错误

问题描述 投票:0回答:1
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

谁能帮我以正确的方式向所有消费者发送消息?

rust watch rust-tokio
1个回答
0
投票

由于这一行,通道的元素类型被推断为

&str
:

let (tx, _rx) = watch::channel("hello");

然后,您发送

val.as_str()
,它返回一个借用于
&str
val
,但是
val
将在循环迭代结束时被销毁。

只需发送自有值 (

String
) 而不是借用的值。您可以通过发送
val
而不是
val.as_str()
来完成此操作。您还必须发送
"hello".to_owned()
而不是
"hello"
才能使类型匹配。

© www.soinside.com 2019 - 2024. All rights reserved.