What is the meaning of 'Temporary'

Hi everyone, I'm new to Rust. I have some questions about the concept of Temporary, and I've done some research on it, but there are a few things I'm still unclear about:

fn main() {
     let s = &String::from("text");
}

Does Rust create a temporary variable containing String::from("text") in the above code? Or does temporary variable here refer to String::from("text")?

If Rust actually creates a 'temporary variable' to hold String::from("text"), will that variable be stored on the stack or the heap? And will String::from("text") be stored on the stack or the heap?

Yes.

The stack.[1]

Rust never creates a heap allocation implicitly. As long as you are using elements of the language syntax and not calling any standard library functions, no new heap allocations are created. There is one heap allocation in your code, caused by calling String::from(); there is not a second one to store the String in.


  1. If you were writing an async fn, then the temporary future would be allocated in the async fn’s future, rather than directly on the stack; that future is itself a value that could be stored in stack or heap but there is still no heap allocation for the variable itself. ↩︎

4 Likes

Thanks for your answer, I appreciate your prompt response :100: