-3
#[derive(Debug)]
struct Position {
    x: i32,
    y: i32,
}

fn main() {
    let pos = Position { x: 4, y: 5 };

    let foo1 = move || {
        println!("{:?}", pos);
    };

    let foo2 = move || {
        println!("{:?}", pos);
    };

    foo1();
    foo2();
}

I got the error message:

error[E0382]: use of moved value: `pos`
  --> src/main.rs:14:16
   |
8  |     let pos = Position { x: 4, y: 5 };
   |         --- move occurs because `pos` has type `Position`, which does not implement the `Copy` trait
9  | 
10 |     let foo1 = move || {
   |                ------- value moved into closure here
11 |         println!("{:?}", pos);
   |                          --- variable moved due to use in closure
...
14 |     let foo2 = move || {
   |                ^^^^^^^ value used here after move
15 |         println!("{:?}", pos);
   |                          --- use occurs due to use in closure
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Yuu
  • 11
  • 1
  • Does this answer your question? [What are move semantics in Rust?](https://stackoverflow.com/questions/30288782/what-are-move-semantics-in-rust) – Svetlin Zarev Aug 03 '21 at 10:17
  • That's not a global value, it's just a regular variable. For *this specific case*, you could choose to [make it a constant](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=4b42b48e79f0b81b558a4727674a6e46) – Shepmaster Aug 03 '21 at 14:06

1 Answers1

0

After your declaration of foo1 the variable pos no longer belongs to main, but has been moved into the foo1 closure.

How to resolve this depends on what you want to achieve. You could implement the Clone trait for your Position struct via #[derive(Debug, Clone)], create a clone for foo1 and use the cloned value instead:

```
let pos_foo1 = pos.clone();
let foo1 = move ||{
    println!("{:?}", pos_foo1);
};
```
FlyingFoX
  • 3,379
  • 3
  • 32
  • 49
  • thank your answers, what if I want to use the same instance to share state in this two closure functions? – Yuu Aug 03 '21 at 12:17
  • Then you need a way to synchronize access to the data. You could do that with a [Mutex](https://doc.rust-lang.org/std/sync/struct.Mutex.html), but it depends on your use case. – FlyingFoX Aug 03 '21 at 12:28