Does Rust Have Garbage Collection? How Does Memory Management Work?

Rust uses a compile-time Ownership system instead of garbage collection to ensure memory safety and performance.

No, Rust does not have garbage collection; it uses a system called Ownership to manage memory at compile time. The compiler enforces three rules: each value has a single owner, there can only be one owner at a time, and when the owner goes out of scope, the value is dropped. This approach ensures memory safety without the runtime overhead of a garbage collector.

fn main() {
    let s = String::from("hello"); // 's' is the owner
    // 's' is dropped here when it goes out of scope
}