为什么在Rust中修改字符串变量时指针的地址没有改变?

Cae*_*133 2 memory pointers rust

我以为在修改字符串时,rust在堆内存中产生了另一个数据。因此,我预计当将值推入字符串变量时,指针地址会发生变化。

fn main() {
    let mut hello = String::from("hello");
    println!("{:?}", hello.as_ptr()); // 0x7fcfa7c01be0
    hello.push_str(", world!");
    println!("{:?}", hello.as_ptr()); // 0x7fcfa7c01be0
}
Run Code Online (Sandbox Code Playgroud)

但是,结果表明并非如此。指针的地址未更改,因此我使用矢量类型对其进行了测试。

fn main() {
    let mut numbers = vec![1, 2, 3];
    println!("{:?}", numbers.as_ptr()); // 0x7ffac4401be0
    numbers.push(4);
    println!("{:?}", numbers.as_ptr()); // 0x7ffac4401ce0
}
Run Code Online (Sandbox Code Playgroud)

矢量变量的指针地址在修改时已更改。字符串和向量类型的内存有什么区别?

jil*_*les 5

Vec<T>并且String可能会保留额外的空间,以避免在每次推送操作中分配。这为推操作提供了分摊的O(1)时间。

碰巧是这样的情况,vec!即保证宏在没有这样的额外空间的情况下创建一个矢量,而String::from(&str)没有这样的保证。

有关更多详细信息,请参见https://doc.rust-lang.org/std/vec/struct.Vec.html#capacity-and-reallocation