【发布时间】:2020-03-19 07:21:14
【问题描述】:
我认为 rust 在修改字符串时会在堆内存中生成另一个数据。因此,当我将值推送到字符串变量时,我预计指针地址会发生变化。
fn main() {
let mut hello = String::from("hello");
println!("{:?}", hello.as_ptr()); // 0x7fcfa7c01be0
hello.push_str(", world!");
println!("{:?}", hello.as_ptr()); // 0x7fcfa7c01be0
}
但是,结果表明并非如此。指针的地址没有改变,所以我用vector类型测试了一下。
fn main() {
let mut numbers = vec![1, 2, 3];
println!("{:?}", numbers.as_ptr()); // 0x7ffac4401be0
numbers.push(4);
println!("{:?}", numbers.as_ptr()); // 0x7ffac4401ce0
}
向量变量的指针地址在修改时发生了变化。字符串和向量类型的内存有什么区别?
【问题讨论】:
-
如果有足够的空间为什么要这样? play.rust-lang.org/…基本测试会给你答案