When a variable goes out of scope in Rust, the compiler automatically calls drop to free the memory if the variable owns heap data like a String, but does nothing if the data was moved or is a stack-allocated type like i32. This cleanup happens immediately when the closing brace } is reached, preventing memory leaks without manual intervention.
fn main() {
let s = String::from("hello"); // s comes into scope
// s goes out of scope here and is dropped
}
fn takes_ownership(some_string: String) {
println!("{some_string}");
} // some_string goes out of scope and `drop` is called