rust / beginner
Snippet
Understanding Ownership: Move Semantics
When you assign s2 = s1 for heap types like String, ownership transfers (moves) to s2. s1 becomes invalid. This prevents double-free bugs and enforces single ownership. Primitives like i32 Copy instead of Move.
snippet.rs
1
2
3
4
5
6
fn main() {let s1 = String::from("hello");let s2 = s1;// println!("{}", s1); // Error: s1 was movedprintln!("{}", s2);}
Breakdown
1
let s1 = String::from("hello")
Creates a String allocated on the heap with value "hello".
2
let s2 = s1
Ownership of the heap data transfers to s2. s1 is no longer accessible.
3
println!("{}", s2)
This works because s2 now owns the data.