Code Example Template
Deep-Dive System Documentation
Memory Rule: Single Owner
Ownership is Rust's most unique feature. It enables complete memory safety without requiring a garbage collector.
The Three Laws of Ownership
- Each value in Rust has an owner (a variable).
- There can only be one owner at a time.
- When the owner goes out of scope, the value is automatically cleaned up (dropped).
Ownership Move Semantics
When you assign a heap-allocated resource (such as a String or Vec) to another variable, or pass it by value to a function, ownership is moved. The original variable is invalidated:
struct Profile {
id: u32,
}
let profile = Profile { id: 1 };
// register_engine takes ownership of profile
register_engine(profile);
// ERROR: profile can no longer be accessed here!
// println!("{}", profile.id);
Why?
Single ownership guarantees that there is exactly one variable responsible for freeing memory. This prevents double-free vulnerabilities and dangling pointers at zero runtime cost.
Quick Reference Guide
let s1 = String::from("hello");
let s2 = s1; // s1 moved here