如何在异步移动循环中使用静态可变引用?

How to use a static mutable reference in a loop with async move?

我的代码具有生命周期为 'static 的可变引用,我正尝试在具有 async move:

的循环中使用它
fn baz(_s: &mut String) {
    // do something
}

fn main() {
    let bar: &'static mut String = Box::leak(Box::new("test".to_string()));
    loop {
        tokio::spawn(async move {
            baz(bar);
        });

        // some conditions here to exit from the loop
    }
}

Rust 编译器建议重新借用,但它在语法上是不正确的,这是我第一次偶然发现:

error[E0382]: use of moved value: `bar`
  --> src/main.rs:8:33
   |
6  |       let bar: &'static mut String = Box::leak(Box::new("test".to_string()));
   |           --- move occurs because `bar` has type `&mut String`, which does not implement the `Copy` trait
7  |       loop {
8  |           tokio::spawn(async move {
   |  _________________________________^
9  | |             baz(bar);
   | |                 --- use occurs due to use in generator
10 | |         });
   | |_________^ value moved here, in previous iteration of loop
   |
help: consider creating a fresh reborrow of `bar` here
   |
8  |         tokio::spawn(async move &mut *{
   |                                 ++++++

如何在这样的循环中使用这个可变引用?我反对在循环中借用 async move 想做一个 copy/clone.

您一次只能拥有一个 (one) &mut,因此为了将其用作共享资源,您必须使用某种同步. Mutex 在这里可能会派上用场。