首页 > 解决方案 > 为什么修改 Rust 中的字符串变量时指针的地址不会改变?

问题描述

我认为 rust 在修改字符串时会在堆内存上生成另一个数据。因此,当我将值推送到字符串变量时,我预计指针地址会发生变化。

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

然而,结果表明并非如此。指针的地址没有改变,所以我用向量类型进行了测试。

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

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

标签: pointersmemoryrust

解决方案


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

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

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


推荐阅读