我正在使用 tokiotokio = { version = "1.17.0", features = ["full"] }
unbounded_channel
通道发送一些 sse 消息,因为我需要从不同的位置发送消息,所以我定义了这样的发送消息函数(这是显示错误的最小重现演示):
use std::sync::{Arc, Mutex};
use tokio::{
sync::mpsc::{UnboundedReceiver, UnboundedSender},
task,
};
#[tokio::main]
async fn main() {
let (tx, rx): (UnboundedSender<String>, UnboundedReceiver<String>) =
tokio::sync::mpsc::unbounded_channel();
task::spawn_blocking(move || {
let shared_tx = Arc::new(Mutex::new(tx));
shared_tx.lock().unwrap().send("l".to_string());
});
tx.send("d".to_string());
}
编译器显示错误:
> cargo build
Compiling rust-learn v0.1.0 (/Users/xiaoqiangjiang/source/reddwarf/backend/rust-learn)
warning: unused variable: `rx`
--> src/main.rs:9:14
|
9 | let (tx, rx): (UnboundedSender<String>, UnboundedReceiver<String>) =
| ^^ help: if this is intentional, prefix it with an underscore: `_rx`
|
= note: `#[warn(unused_variables)]` on by default
error[E0382]: borrow of moved value: `tx`
--> src/main.rs:15:5
|
9 | let (tx, rx): (UnboundedSender<String>, UnboundedReceiver<String>) =
| -- move occurs because `tx` has type `UnboundedSender<String>`, which does not implement the `Copy` trait
10 | tokio::sync::mpsc::unbounded_channel();
11 | task::spawn_blocking(move || {
| ------- value moved into closure here
12 | let shared_tx = Arc::new(Mutex::new(tx));
| -- variable moved due to use in closure
...
15 | tx.send("d".to_string());
| ^^^^^^^^^^^^^^^^^^^^^^^^ value borrowed here after move
For more information about this error, try `rustc --explain E0382`.
warning: `rust-learn` (bin "rust-learn") generated 1 warning
error: could not compile `rust-learn` due to previous error; 1 warning emitted
我已经尝试添加.as_ref()
但shared_tx
仍然没有解决这个问题。我应该怎么做才能解决这个问题?这是cargo.toml:
[package]
name = "rust-learn"
version = "0.1.0"
edition = "2018"
[dependencies]
tokio = { version = "1.17.0", features = ["full"] }
serde = { version = "1.0.64", features = ["derive"] }
serde_json = "1.0.64"
MPSC 代表多个生产者,单个消费者。您不需要将发件人包装在 中
Arc<Mutex>
,只需将其包装即可clone()
。