Move Semantics
An assignment will transfer ownership between variables:
1. fn main() {
2. let s1: String = String::from("Hello!");
3. let s2: String = s1;
4. println!("s2: {s2}");
5. // println!("s1: {s1}");
6. }
- 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.
- 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, clones are explicit (by using
clone).
