&String storage whose memory address?

As we all know, String is a struct type, and the str exist at heap. So if we use &String and print the memory address. It's struct's address or str's address?

Not necessarily. It can also be at stack (created from [u8]) or mapped from the executable itself (like literals).

If we use &T and print it as {:p}, we print the address where the reference is pointing to, i.e. address of T. This is not specific to String, this is just what "pointer" format specification means.

1 Like

yes, str could also exist at stack. But from my understanding, when we use String to use a str, this str could only created at heap. Is my understanding right?
when it comes to basic type, i'am sure &T storage an address which pointing to T. But String's architecture is different from usual variable. please look at my picture.

It's String's memory address on the stack.
Internally, String contains another pointer to the str on the heap.

Also you can paste code to this forum using triple backticks ``` like this:

fn main() {
    let x = String::from("hello");
    let p = &x;
    let q = p.as_str();
    println!("Address of the String on the stack: {p:p}");
    println!("Address of the str on the heap {q:p}");

I got it, sir. Thank you very much!

That diagram is not correct. A &String would be a pointer to the String struct on the left and not contain the length. The pointer and length thing on the right would be a &str and can point to the heap, or to the stack or to static memory or wherever.

An alternative diagram.

The pointer in the String points to the heap if allocation has occurred, but that's a library-level detail, not something intrinsic to the language or a primitive type within it. Rust primitives like pointers don't "know" what a heap is or if they point to the heap or the stack, etc.

There is also a diagram for this in the book.

@zzzdjkk I strongly recommend reading chapter 4 of the book.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.