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 s1 to s2 transfers ownership.
  • The data was moved from s1 and s1 is no longer accessible.
  • When s1 goes out of scope, nothing happens: it has no ownership.
  • When s2 goes 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).