capypad
0 day streak
rust / beginner
Snippet

Understanding Ownership

Rust uses an ownership system to manage memory efficiently without garbage collection. When you assign s1 to s2, ownership of the data moves to s2, and s1 is no longer valid. This prevents double-free errors. For read-only access, you can borrow a reference with &, which allows multiple references without transferring ownership.

snippet.rs
rust
1
2
3
4
5
6
7
8
9
10
11
12
13
fn main() {
let s1 = String::from("hello");
let s2 = s1;
// println!("{}", s1); // Error: s1 is no longer valid
println!("{}", s2);
let s3 = String::from("world");
let s4 = &s3;
println!("{}", s3); // s3 is still valid, s4 just borrows it
println!("{}", s4);
}
Breakdown
1
let s1 = String::from("hello");
Creates a String owned by s1
2
let s2 = s1;
Ownership moves to s2, s1 is now invalid
3
let s4 = &s3;
Creates a borrowing reference, s4 does not own the data
4
println!("{}", s3);
s3 is still valid because only a reference was borrowed