Answer#
In C++ a move is an optimisation you ask for with std::move. The source object is still there afterwards, in a "valid but unspecified" state, and the language lets you use it. Every class that supports moving needs a move constructor, a move assignment and a moved-from state to design and test.
In Rust a move is the default for every type that is not Copy, and the compiler treats the source as gone. There is nothing to design: no move constructor to write, no empty state to maintain, and no destructor call for the moved-from variable. Using the old name afterwards is a compile error:
fn consume(v: Vec<i32>) -> usize {
v.len()
}
fn main() {
let v = vec![1, 2, 3];
let n = consume(v);
println!("{n} {}", v.len());
}error[E0382]: borrow of moved value: `v`
--> src/main.rs:8:24
|
6 | let v = vec![1, 2, 3];
| - move occurs because `v` has type `Vec<i32>`, which does not implement the `Copy` trait
7 | let n = consume(v);
| - value moved here
8 | println!("{n} {}", v.len());
| ^ value borrowed here after move
|
help: consider cloning the value if the performance cost is acceptable
|
7 | let n = consume(v.clone());
| ++++++++The message was shortened (and the file name shown as src/main.rs; it was compiled from a scratch file). It shows the three ways forward: pass a reference (&v) if the function only reads, move and stop using the name, or clone() to make an explicit copy.
When you do want a valid replacement left behind (what C++ gives you automatically, with a moved-from empty std::string), say so with std::mem::take or std::mem::replace:
fn consume(v: Vec<i32>) -> usize {
v.len()
}
fn main() {
let mut name = String::from("config");
let taken = std::mem::take(&mut name); // moves the text out and leaves a valid empty String behind
println!("taken={taken:?} left={name:?}");
let old = std::mem::replace(&mut name, String::from("fresh"));
println!("old={old:?} now={name:?}");
let v = vec![1, 2, 3];
let n = consume(v.clone()); // an explicit copy, visible in the code
println!("{n} {}", v.len());
}taken="config" left=""
old="" now="fresh"
3 3How to do it#
- Where C++ copied an object because the copy constructor was implicit, Rust makes you write
.clone(). Look at each one: do you need the copy, or can the function take a reference? - Where C++ used
std::move(x), writex(the move is automatic). Remove later uses ofx, or restructure. - Where C++ code relies on a moved-from object being reused (a buffer that is emptied and refilled in a loop), use
mem::take, or clear the collection with.clear()and reuse it. - Where a type is small and plain (numbers, a pair of coordinates), derive
CopyandClone, and the move question disappears: copies are cheap and implicit.
Common mistakes#
- Adding
.clone()at every error. Each is a real copy. Count them in hot code (see the thread on why a port can be slower). - Expecting a destructor to run for a moved-from value. In Rust the value is dropped once, by its final owner.
- Moving out of a vector element by index (
let x = v[0];for aString). The compiler rejects it because the vector still owns the element; usev.remove(0),std::mem::take(&mut v[0]), or borrow.
Related questions#
Is a Rust move expensive?#
A move copies the value's bytes (a Vec is a pointer, a length and a capacity) and does not touch the heap data. The compiler may then remove even that copy. This thread did not measure it.
How does this relate to copy elision and RVO?#
Returning a value from a function is a move in Rust, with no special rule to learn.
Sources#
- The Rust Book, "What Is Ownership?": https://doc.rust-lang.org/book/ch04-01-what-is-ownership.html
std::mem::take: https://doc.rust-lang.org/std/mem/fn.take.html