Variable Scope in Rust
When you declare a variable in Rust, its scope begins immediately at the point of declaration and lasts until the end of the enclosing block. For example:x is in scope throughout the current block. Once the block terminates, x goes out of scope and Rust automatically cleans up its memory.
Ownership in Rust
Rust’s ownership model is key to its memory safety guarantees. When an owning variable goes out of scope, Rust automatically frees the memory it holds by calling a special function calleddrop.
Consider the String type, which represents a mutable, growable piece of text stored on the heap. Unlike fixed-size types, a String requires runtime memory allocation because its size isn’t known at compile time. Once a String is no longer needed, its allocated memory is automatically returned to the allocator.
The following example demonstrates this behavior. The variable s is initialized using String::from. When s leaves scope at the end of the block, Rust automatically deallocates the associated memory:
Rust’s ownership model avoids the overhead of garbage collection by ensuring that resources are automatically cleaned up when they are no longer needed, reducing the risk of memory leaks and errors.