#Getting confused over moving and ownership (example below)

1 messages · Page 1 of 1 (latest)

scenic vault
#
fn grab_server_time() -> String {
    let mut response_vector: Vec<String> = vec![];
    let url = "https://".to_string();

    let _state = spawn_local(async move {
        response_vector.push(torrent::get(url).await.unwrap().clone());
    });

    response_vector.first().unwrap().clone()
}

I'm trying to capture a string from a future call in a thread.
response_vector is supposed to put a cloned copy of the string.

The compilation error is saying it's due to deref coercion to [String]

What could I try here to save the string value in the vector?


error[E0382]: borrow of moved value: `response_vector`
    --> src/main.rs:45:5
     |
39   |       let mut response_vector: Vec<String> = vec![];
     |           ------------------- move occurs because `response_vector` has type `Vec<String>`, which does not implement the `Copy` trait
40   |       let url = "https://".to_string();
41   |       let _state = spawn_local(async move {
     |  ______________________________-
42   | |         response_vector.push(torrent::get(url).await.unwrap().clone());
     | |         --------------- variable moved due to use in generator
43   | |     });
     | |_____- value moved here
44   |
45   |       response_vector.first().unwrap().clone()
     |       ^^^^^^^^^^^^^^^^^^^^^^^ value borrowed here after move
     |
     = note: borrow occurs due to deref coercion to `[String]`
note: deref defined here
    --> C:\Users\Nils\.rustup\toolchains\stable-x86_64-pc-windows-msvc\lib/rustlib/src/rust\library\alloc\src\vec\mod.rs:2659:5
     |
2659 |     type Target = [T];
     |     ^^^^^^^^^^^
help: consider cloning the value if the performance cost is acceptable
     |
43   |     }.clone());
     |      ++++++++

chilly orchid
#

-errors First, always remember to share full errors, it helps us help you

dawn spadeBOT
#

If you're getting large or confusing errors please post the full error message from cargo check in a code block instead of the errors in your IDE so that we can understand your problem better:

```rust
// error from cargo check here
```

chilly orchid
#

When you specify async move, it takes ownership of response_vector (hence the move). That means nothing else can use it. However, you later try to use it at the last line, which causes the error

scenic vault
#

I've seen syntax for an anonymous function to take an argument
Could I do something like this? (async move {})(response_vector: &Vec<String>)

chilly orchid
#

That won't work here, because there's no way to get spawn_local to give the argument, nor any way to get the Vec back after the thread is done

scenic vault
#

back to it then

#

thank you