Rust ownership
Created By: chatGPT
Ownership is a core concept in Rust that governs how memory is managed. In Rust, every piece of data has a single owner, and when the owner goes out of scope, the data is automatically cleaned up. This ensures memory safety without needing a garbage collector. Here's a typical example to illustrate this:
fn main() {
let s1 = String::from("Hello"); // s1 owns the String
let s2 = s1; // Ownership of the String moves to s2
// println!("{}", s1); // This would cause a compile-time error
println!("{}", s2); // This is valid
}
You can also use references to avoid moving ownership. This allows you to borrow values without taking ownership. Here's an example of mutable and immutable references:
fn main() {
let mut s = String::from("Hello");
let r = &s; // Immutable reference
println!("{}", r);
let r_mut = &mut s; // Mutable reference
r_mut.push_str(" World!");
println!("{}", r_mut);
}
It's important to remember that you can have either multiple immutable references or one mutable reference at a time, but not both. This rule prevents data races at compile time. Here's what happens when you violate this rule:
fn main() {
let mut x = 5;
let r1 = &x;
let r2 = &mut x; // Error: cannot borrow `x` as mutable because it is also borrowed as immutable
println!("{}", r1);
}