Questions about an example in The Rust Programming Language book

Hello everyone, I am a newbie in Rust and I am learning Rust through 《The Rust Book》

In the section on building a multi-threaded web server, the following examples exist

My question is why does the closure passed by the thread :: spawn function require the move keyword, and which external variable has moved ownership?

The call receiver.lock() takes &Mutex<...>, so it would normally only require a borrow. Because of this, it is not normally moved into the closure. id is in a similar situation: println! only borrows arguments you pass into it, so id is only ever borrowed too, so it would also normally remain owned by the external environment.

But in order to spawn it on a thread, the closure must own all the things it uses, and can't borrow any from the external environment. So the move keyword forces the closure to move/take ownership of everything it uses. Specifically, receive and id.

2 Likes

thank you very much

1 Like

If you want to read more about closures, see my blog post on them

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.