Rust ensures security by enforcing memory safety at compile time through its ownership system, preventing common vulnerabilities like buffer overflows and data races without runtime overhead. The compiler checks ownership rulesβeach value has one owner, and data is dropped when the owner goes out of scopeβto guarantee that invalid memory access or use-after-free errors cannot occur. This approach eliminates the need for a garbage collector while providing safety guarantees that traditional systems languages lack.
fn main() {
let s1 = String::from("hello");
let s2 = s1; // Ownership moves to s2, s1 is invalid
// println!("{s1}"); // Error: use of moved value
println!("{s2}"); // Valid
}