rust - 在 Rust 中,向量如何在编译时既是动态的又是已知的?

标签 rust

我对 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 of T at compile time (that is, how many bytes are needed to store a T?). 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, the Box 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/

相关文章:

rust - 如何检查切片中是否有重复项?

shell - fzf,stdin出现问题,并从rust :调用程序

Rust,2 个具有重叠私有(private)函数的 crate

objective-c - 在Rust中使用Objective-C时管理 cocoa 内存的正确方法

data-structures - 从可变结构字段的值调用可变方法

rust - 如何更新 Bytes/BytesMut 的一部分?

rust - rss crate 已安装,但找不到函数 Channel::from_url

rust - 在 From 实现中 panic 是惯用的吗?

rust - 在解析包版本时,我可以强制使用依赖项的 Cargo.lock 吗?

string - 我怎样才能返回一个字符串向量?