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
}
然而,结果表明并非如此。指针的地址没有改变,所以我用向量类型进行了测试。
fn main() {
let mut numbers = vec![1, 2, 3];
println!("{:?}", numbers.as_ptr()); // 0x7ffac4401be0
numbers.push(4);
println!("{:?}", numbers.as_ptr()); // 0x7ffac4401ce0
}
向量变量的指针地址在修改时被更改。字符串和向量类型的内存有什么区别?
解决方案
Vec<T>
并且String
可能会保留额外的空间以避免在每次推送操作上分配。这为推送操作提供了平摊的 O(1) 时间。
碰巧的是,vec!
宏保证创建一个没有额外空间的向量,而String::from(&str)
没有这样的保证。
有关更多详细信息,请参阅https://doc.rust-lang.org/std/vec/struct.Vec.html#capacity-and-reallocation。
推荐阅读
- google-apps-script - Google 表格中的自动增量数据验证
- docker - 使用用户名/密码使用 nfs 挂载网络共享
- javascript - Wordpress 网站未反映 Javascript 更改
- ios - Swift - 数组过滤器然后更新主数组
- azure-devops - Azure devops .netcore 失败,但在 Visual Studio 中构建良好
- spring-saml - 创建名为 'org.springframework.security.saml.SAMLBootstrap#0' 的 bean 时出错
- excel - 计算列范围内两次之间的差异
- r - ggplot - 添加垂直线
- python - 如何选择列表中的特定元素并使用它们(Python)
- sql-server - 将数据解析为单独的列