Welcome to WordPress. This is your first post. Edit or delete it, then start writing!
fn main() {
// Ownership: Each value has a single owner
let s1 = String::from("hello");
// Move semantics: ownership transferred to s2
let s2 = s1;
// println!("{}", s1); // Compile error: value moved
println!("s2 owns: {}", s2);
// Clone for deep copy when needed
let s3 = s2.clone();
println!("s2: {}, s3: {}", s2, s3);
// Borrowing: immutable references
let len = calculate_length(&s3);
println!("Length of '{}' is {}", s3, len);
// Mutable borrowing: exclusive access
let mut s4 = String::from("hello");
append_world(&mut s4);
println!("After mutation: {}", s4);
// Multiple immutable borrows allowed
let r1 = &s4;
let r2 = &s4;
println!("r1: {}, r2: {}", r1, r2);
// Demonstrates non-lexical lifetimes (NLL)
{
let r3 = &s4;
println!("r3: {}", r3);
} // r3 scope ends, can now mutably borrow
let r4 = &mut s4;
r4.push_str("!");
println!("Final: {}", r4);
}
fn calculate_length(s: &String) -> usize {
s.len()
// s goes out of scope but doesn't drop the String
// because it doesn't have ownership
}
fn append_world(s: &mut String) {
s.push_str(", world");
// Mutable reference allows modification
}