ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

Rust Tutorial• 8 min read

The Ownership System: Rust's Crown Jewel

The 3 golden rules of ownership, stack vs heap, and move semantics

Ownership is Rust’s most unique feature. It governs how memory is allocated, transferred, and freed without a garbage collector.

The 3 Golden Rules of Ownership

1Each value in Rust has an OWNER (a variable).
2There can only be ONE owner at a time.
3When the owner goes OUT OF SCOPE, the value is automatically DROPPED (deallocated).

Move Semantics: Assigning a heap value (String) to another variable MOVES ownership; the original variable becomes invalid immediately!

Ownership Move in Action
fn main() {
    let s1 = String::from("Codexia");
    
    // Ownership is MOVED to s2!
    let s2 = s1;

    // println!("{}", s1); // COMPILE ERROR: s1 was moved!
    println!("s2 owns the memory: {}", s2);
} // s2 goes out of scope here: memory freed automatically via drop()
ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

What happens to the variable `s1` after executing `let s2 = s1;` where `s1` is a heap-allocated `String`?