我对 documentation for vectors in Rust 中似乎相互矛盾的陈述感到困惑:
A ‘vector’ is a dynamic or ‘growable’ array, implemented as the standard library type
Vec<T>
.
和
Vectors store their contents as contiguous arrays of
T
on the heap. This means that they must be able to know the size ofT
at compile time (that is, how many bytes are needed to store aT
?). The size of some things can't be known at compile time. For these you'll have to store a pointer to that thing: thankfully, theBox
type works perfectly for this.
Rust 向量是动态增长的,但我看不出这与必须在编译时知道它们的大小的说法相符。
自从我使用低级语言以来我已经有一段时间了,在这种语言中我必须考虑内存分配,所以我可能遗漏了一些明显的东西。
最佳答案
注意措辞:
they must be able to know the size of
T
这表示必须知道单个元素的大小。元素的总数以及分配的内存总量是未知的。
当向量分配内存时,它说“我想存储 12 个 FooBar
结构。一个 FooBar
是 24 字节,因此我需要总共分配 288 字节”。
12是向量的动态容量,24是一个元素(T
)的静态大小。
关于rust - 在 Rust 中,向量如何在编译时既是动态的又是已知的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43100123/