capypad
0 day streak
rust / beginner
Snippet

Understanding Ownership: Move Semantics in Rust

In Rust, ownership is a unique feature that manages memory without garbage collection. When you assign s1 to s2, the ownership of the heap data is 'moved' from s1 to s2. After this move, s1 is no longer valid. This prevents double-free errors and ensures memory safety at compile time.

snippet.rs
rust
1
2
3
4
5
6
fn main() {
let s1 = String::from("hello");
let s2 = s1;
// println!("{}", s1); // This would cause a compile error!
println!("{}", s2); // This works fine
}
Breakdown
1
let s1 = String::from("hello");
Creates a String on the heap with value 'hello'
2
let s2 = s1;
Ownership of the heap data moves from s1 to s2
3
println!("{}", s2);
s2 is valid and can access the data