rust / beginner
Snippet
Ownership Rules at a Glance
Ownership is Rust's unique memory management system. When you assign s1 to s2, ownership moves. s1 is no longer valid. Borrowing with & allows referencing without transferring ownership.
snippet.rs
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 finelet s3 = String::from("world");let s4 = &s3; // Borrowing with referenceprintln!("{} and {}", s3, s4); // Both accessible}
Breakdown
1
let s2 = s1;
Ownership of s1 moves to s2; s1 is invalidated
2
// println!("{}", s1); // ERROR
Commented line would cause compile error
3
let s4 = &s3;
Creates a reference to s3 without taking ownership
4
println!("{} and {}", s3, s4);
Both s3 and s4 are valid because of borrowing