在声明String类型时,我有一个疑问,栈区和堆区的内存是如何分配的。
我认为,内存分配图像如下。
let s = String::from("hello world");
(A) (B)
+======================+----- static memory -------+======================+
| ... | | "hello world"(12) |
| | | ... |
+======================+------ stack memory -------+======================+
| s(24) | | s(24) |
| data addr | | data addr |
| length | | length |
| capacity | | capacity |
| ... | | ... |
| | | |
| ... | | |
| "hello world"(12) | | ... |
+======================+------- heap memory -------+======================+
哪种情况是正确的?
我知道文字字符串在编译时存储在静态区域中。然而,Rust 文档指出 String 类型等同于 Vec。 Vec 类型将其所有元素存储在堆上,所以我很困惑场景 A 是否正确。
都不正确。
首先,
"hello world"
只有 11 个字节。 Rust 不会以空字符结尾字符串。
本质上,
"hello world"
是存储在二进制静态内存中的str
,它从静态内存复制到堆内存中。 String
结构体存储指向堆内存的指针、字符串的长度以及分配的容量。
伪代码:
static_memory = {
hello_world_contents: str = "hello world"=
hello_world_literal: &str = (&hello_world_contents, 11)
}
def String_from_strref(text: &str) -> String:
(pointer, length) = text
heap_pointer = malloc(length)
capacity = memcpy(heap_pointer, pointer, length)
return (heap_pointer, length, capacity)
let s = String_from_strref(hello_world_literal)