Move Semantics Explained
Move Semantics Explained
When a heap-backed value is assigned to another binding, passed to a function, or returned from a function, ownership is moved.
fn main() {
let s1 = String::from("orders");
let s2 = s1; // s1 is MOVED to s2
// println!("{}", s1); // COMPILE ERROR: value borrowed here after move
println!("s2 owns the heap buffer: {}", s2);
}Why Rust Moves Instead of Shallow Copying
If s1 and s2 both owned the same heap pointer, when both went out of scope, they would attempt to free the same memory twice—a catastrophic double free bug. Rust prevents this by invalidating s1 at compile time with zero runtime cost.