liveBook · Manning

Move

As explained in Idiomatic Rust

Move semantics transfer ownership of a value into a new binding or operation rather than copying the value.

A move transfers ownership of a value instead of copying or cloning it. It can happen when a value is assigned, passed to a function, captured by a closure, or returned; values passed by value move when their type does not implement Copy. section 4.2.1

Use the ownership transfer deliberately:

  • Pass by value when the callee needs ownership, such as when it will return the value or incorporate it into a new result. References usually suit temporary access; mutable references allow mutation without transferring ownership. section 4.2.3
  • A move closure captures values by ownership. If it consumes a captured value, it implements FnOnce and cannot be called again after that value has been consumed. The move keyword is optional when Rust infers the same capture, but makes intent explicit. section 3.2.2

Return a moved value

A function can take ownership of a String, reverse it, and return a new String. Returning multiple results can transfer them together in a tuple. section 4.2.1

Listing 3.3 Closure with move
let consumable = String::from("cookie");
let consumer = move || consumable;
consumer();
// consumer(); error!

A closure takes ownership of a String and returns it; calling the consumer again is invalid because the value has already been consumed. section 3.2.2

How Idiomatic Rust covers it

How deep it goes
Defines moves across calls, closures, assignment, and returns, then gives practical guidance for choosing value or reference passing.
Examples
Demonstrates reversing a String by value, returning multiple results in a tuple, and consuming a captured String in a closure.
What you can do after
Apply moves to transfer non-Copy values into functions or closures, return ownership, and judge when references are preferable.
How it connects
Connects moves with closures, FnOnce, Copy, and borrowing through references.

Also explained in

Compare how 5 books explain move →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Idiomatic Rust. The section links point to the parts of the book it draws on.