Undesrtanding Ownership in Rust
Rust employs a unique ownership system for memory management that differs from both garbage collection and manual memory management approaches.
Core Ownership Rules
- Each value in Rust has exact one owner
- Only one owner can exist at any given time
- Values are dropped when their owner goes out of scope
Ownership and Functions
Passing values to functions follows similar semantics to variable assignment. The behavior depends on whether the value is stored on the stack or heap:
fn main() {
let stack_value = "stack_data";
process_stack(stack_value);
println!("{}", stack_value); // Still valid
let heap_value = String::from("heap_data");
process_heap(heap_value);
println!("{}", heap_value); // Error: value borrowed after move
}
fn process_stack(data: &str) {
println!("Processing: {}", data);
}
fn process_heap(data: String) {
println!("Processing: {}", data);
}
Return Values and Scope
Ownership can also be transferred through return values:
fn main() {
let first = create_resource(); // Ownership transferred
let second = String::from("resource");
let third = transfer_ownership(second); // Ownership transferred
}
fn create_resource() -> String {
let resource = String::from("new_resource");
resource // Ownership returned
}
fn transfer_ownership(resource: String) -> String {
resource // Ownership returned
}