Stack and Heap Example
Creating a String
puts fixed-sized metadata on the stack and dynamically sized data, the actual string, on the heap:
fn main() { let s1 = String::from("Hello"); }
-
指出
String
底层由Vec
实现,因此它具有容量和长度,如果值可变,则可以通过在堆上重新分配存储空间进行增长。 -
如果学员提出相关问题,你可以提及我们不仅能使用[系统分配器]在堆上分配底层内存,还能使用 Allocator API 实现自定义分配器
-
我们可以使用
unsafe
代码检查内存布局。不过,你应该指出,这种做法不安全!fn main() { let mut s1 = String::from("Hello"); s1.push(' '); s1.push_str("world"); // DON'T DO THIS AT HOME! For educational purposes only. // String provides no guarantees about its layout, so this could lead to // undefined behavior. unsafe { let (ptr, capacity, len): (usize, usize, usize) = std::mem::transmute(s1); println!("ptr = {ptr:#x}, len = {len}, capacity = {capacity}"); } }