0
votes

The following is written in the Rust documentation:

let s1 = String::from("hello");
let s2 = s1;

When we assign s1 to s2, the String data is copied, meaning we copy the pointer, the length, and the capacity that are on the stack. We do not copy the data on the heap that the pointer refers to.

When I run the following code,

let s1 = String::from("aa");
let p2 = &s1;
println!("p2:{:p}", p2);
let s2 = s1;
let p3 = &s2;
println!("p3:{:p}", p3);

Output:

p2:0x7ffc1bd2e730
p3:0x7ffc1bd2e7a0

Why is the address pointed by p2 and the address pointed by p3 not the same?

1
Those are the addresses to each of the String struct values on the stack, not the string itself. That output pretty much proves that the documentation is correct. - E_net4 the voter
Why is the address pointed by p2 and the address pointed by p3 should be different ? - Stargateur

1 Answers

1
votes

s1 is a struct that hold: * the length of the string (i.e. 2 for aa) * the capacity of the string (i.e. at least 2 for aa, since there are already 2 characters in there) * a pointer to the memory containing actual characters

Now, if you move s1 to s2, the length and the capacity and the pointer are transferred to s2. But it's nowhere said that s2 occupies the same location in memory as s1. This is what you observe in your program.

However, since only the pointer is moved over to s2, it still refers to the same memory containing the actual characters. This can be observed by examining as_bytes:

fn main() {
    let s1 = String::from("aa");
    println!("p2:{:p}", s1.as_bytes());
    let s2 = s1;
    println!("p2:{:p}", s2.as_bytes());
}

The above program spits out the same memory address.