1

I have code with a mutable reference with the 'static lifetime and I am trying to use it in the loop which has 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
    }
}

The Rust compiler suggests reborrowing, but it is syntactically incorrect, the first time I've stumbled on that:

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 *{
   |                                 ++++++

How I can use this mutable reference in such a loop? I'm fighting against borrowing in the loop and async move wanting to do a copy/clone.

4
  • 3
    even if you leak it, you can only have a &mut at a time, so this is never gonna work. You should use some kind of synchronization, probably a Mutex Commented May 10, 2022 at 16:36
  • 2
    Fill a bug for the invalid suggestion, please. Commented May 10, 2022 at 16:44
  • @Netwave Thank you. You are absolutelly right. Haven't thought about it. CAn you please post the answer, so I can accept it. Commented May 10, 2022 at 16:46
  • @ChayimFriedman Done github.com/rust-lang/rust/issues/96908 Commented May 10, 2022 at 16:52

1 Answer 1

3

You can only have a (one) &mut at a time, so in order to use it as a shared resource you have to use some kind of synchronization. A Mutex may come in handy here.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.