移动参考后参考前不相同

after move reference not same before reference

Rust 文档中写了以下内容:

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.

当我运行下面的代码时,

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

输出:

p2:0x7ffc1bd2e730
p3:0x7ffc1bd2e7a0

为什么p2指向的地址和p3指向的地址不一样?

s1 是一个 struct,它包含: * 字符串的长度(即 aa 为 2) * 字符串的容量(即 aa 至少为 2,因为那里已经有 2 个字符) * 指向包含实际字符的内存的指针

现在,如果将 s1 移动到 s2,长度和容量以及指针将转移到 s2。但是没有任何地方说 s2 在内存中与 s1 占据相同的位置。这就是您在程序中观察到的。

但是, 因为只有指针移到了 s2,它仍然指向包含实际字符的同一内存。这可以通过检查 as_bytes:

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

上面的程序吐出相同的内存地址。