How it works...
Threads in Rust behave a lot like regular functions: they can take ownership and operate on the same syntax as closures (|| {} is an empty/noop function without parameters). Therefore, we have to treat them like we treat functions and think of them in terms of ownership and borrowing, or more specifically: lifetimes. Passing a reference (the default behavior) into this thread function makes it impossible for the compiler to keep track of the validity of the reference, which is a problem for code safety. Rust solves this by introducing the move keyword.
Using the move keyword changes the default behavior of borrowing to moving the ownership of every variable into the scope. Hence, unless these values implement the Copy trait ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access