Move Semantics
An assignment will transfer ownership between variables:
fn main() {let s1: String = String::from("Hello!");let s2: String = s1;println!("s2: {s2}");// println!("s1: {s1}");}
- The assignment of
s1tos2transfers ownership. - The data was moved from
s1ands1is no longer accessible. - When
s1goes out of scope, nothing happens: it has no ownership. - When
s2goes out of scope, the string data is freed. - There is always exactly one variable binding which owns a value.
Speaker Notes
-
Mention that this is the opposite of the defaults in C++, which copies by value unless you use
std::move(and the move constructor is defined!). -
In Rust, your clones are explicit (by using
clone).