In this lesson, we will explore how Rust handles immutable, mutable, and dangling references. Understanding these concepts is crucial for writing safe and efficient Rust code.Documentation Index
Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
Use this file to discover all available pages before exploring further.
Immutable References
Immutable references allow you to read data without modifying it. You can have multiple immutable references to the same data, which is especially useful for concurrent read operations. Below are two examples demonstrating immutable references on both stack-allocated and heap-allocated data.Example 1: Stack-Allocated Data
In the following example, an integer is stored on the stack. Two immutable references are created using the& operator:
Example 2: Heap-Allocated Data
This example works with a string stored on the heap. Again, two immutable references are created for the same string:Mutable References
Mutable references permit you to modify the data they point to. Rust enforces a strict rule: you can only have one mutable reference to a particular piece of data at a time. This rule prevents data races and ensures memory safety. Consider the following example where a string is modified through a mutable reference:r allows the string s to be safely modified.
Dangling References
Dangling references occur when a reference points to memory that has been deallocated. Rust’s ownership system and borrow checker prevent dangling references at compile time, ensuring memory safety.
Although the diagram above provides a visual explanation, the code example below further illustrates how dangling references can occur in Rust.
x is declared within an inner block, and a reference to x is assigned to r outside that block:
x is defined inside an inner block and then goes out of scope, which would leave r as a dangling reference. However, Rust’s borrow checker prevents this issue, ensuring that references do not outlive the data they point to.
If you try to compile the code above, you will see an error similar to the following:
r is being used outside the lifetime of x, preventing potential undefined behavior.