Course contentsShow
← Rust
Lesson 203 of 1,9103. Borrowing and ReferencesFree lesson

References to Temporary Values

Analyze the lifetime extension rules when assigning a temporary to a reference.

In this lesson, you will learn how Rust safely handles references to values that don't have a name of their own—often called "temporary values."

The Life of a Temporary

When you create a value in an expression, like adding two numbers or calling a function, that value doesn't have a variable name. It exists only for the duration of that specific expression. Usually, these values are dropped as soon as the expression finishes.

However, if you take a reference to a temporary value, the compiler steps in to help. It realizes that if the temporary disappeared immediately, your reference would instantly become a dangling pointer (which is unsafe!).

Lifetime Extension

To prevent memory errors, Rust applies a rule called lifetime extension. If you assign a temporary value to a reference, Rust will automatically extend the lifetime of that temporary value to match the scope of the reference.

Look at this example:

fn main() {
    // The expression "10 + 20" creates a temporary value (30).
    // Because we store a reference to it, Rust extends 
    // the life of that 30 until the end of this scope.
    let x = &(10 + 20);
    
    println!("The value is: {}", *x);
} 

In the code above, the integer 30 is created, and the reference x points to it. Without lifetime extension, the 30 would vanish the moment the line ended. Instead, Rust keeps that temporary value alive until x goes out of scope at the end of the main function.

Important Constraints

It is important to remember that this only works for simple assignments to references. If you pass a temporary value into a function, the lifetime is not extended in the same way; it only lives for the duration of that function call. If that function tries to return a reference to that temporary, the compiler will stop you because the temporary will be destroyed once the function returns.

The compiler's goal is always to ensure that a reference never outlives the data it points to, even when that data is just a fleeting calculation.

Key Takeaway: When you take a reference to a temporary value, Rust automatically extends the lifetime of that value to match the scope of the reference, ensuring your memory remains safe and valid.