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. ↩︎

6 Likes

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

I think this is first transformed to something like:

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

The variables are on the stack but s_tmp is a fat pointer pointing to the heap.

In the playground at least, that's what the MIR looks like at a glance.

1 Like

Thanks for your reply.

I'm not sure about this, as I haven't seen anyone talk about what you're referring to (or maybe they have, but I haven't found them yet). I'm still struggling with this :melting_face:

I'm still not sure about the following, when we use the term 'Temporary', what are we referring to? What we're referring to String::from("text"), or are we referring to the temporary variable that Rust creates to hold the String::from("text")?

I see some people use Temporary variable, some use Temporary value, some use Temporary memory. I'm really confused about how they use different names.

The syntax of & is &Place_Expression. Here, a value expression is passed, so it creates a temporary variable. Temporary in the sense that it has a scope and will be freed eventually, unless it is promoted to static in which case it outlives the program.

That's just my current understanding, but may be wrong.

1 Like

I think I need to think hard and learn more about the underlying concepts involved to try to solve these questions. Because I know that I lack the basic knowledge of the related concepts.

Thanks again so much for your reply :heart: