capypad
0 day streak
rust / beginner
Snippet

Understanding Ownership and Move Semantics

Rust uses ownership to manage memory. When you assign s1 to s2, ownership of the String's heap data transfers from s1 to s2. After the move, s1 is no longer valid. Use .clone() if you need an independent copy of the data.

snippet.rs
rust
1
2
3
4
5
6
7
8
9
10
11
fn main() {
let s1 = String::from("hello");
let s2 = s1; // s1 is moved to s2
// println!("{}", s1); // This would error!
println!("{}", s2); // This works fine
let s3 = String::from("world");
let s4 = s3.clone(); // Deep copy, both valid
println!("s3: {}, s4: {}", s3, s4);
}
Breakdown
1
let s1 = String::from("hello");
Creates a String allocated on the heap
2
let s2 = s1;
Ownership moves to s2; s1 is now invalid
3
s1 would error
Using s1 after move triggers compile error
4
.clone()
Creates a deep copy; both s3 and s4 are valid