capypad
0 day streak
rust / beginner
Snippet

Understanding Ownership: The Move

In Rust, when you assign a complex type like a String to another variable, the data is 'moved' to the new owner. The original variable becomes invalid.

snippet.rs
rust
1
2
3
4
5
let s1 = String::from("hello");
let s2 = s1;
 
// println!("{}", s1); // This would cause a compile error
println!("{}", s2);
Breakdown
1
let s2 = s1;
The ownership of the string is moved from s1 to s2.
2
// println!(..., s1);
Accessing s1 here is illegal because its value was moved.