首先,我将发表一些类似的问题,但不一样(尽管有类似的标题和主题),如果你在另一个帖子中找到了我的问题的答案,请在 comments 中通知我,我真的找不到.

Question Reason
Use `Option` to maybe allocate? Although I understand that Option does not occupy the total space of 算法 until there is Some, I am referring to an array of Option elements that will most likely be allocated on the Heap instead of a simple Option
https://stackoverflow.com/questions/47876592/what-is-the-most-memory-efficient-array-of-nullable-vectors-when-most-of-the-sec He is making reference to a type of dynamic allocation, which is vec, so, despite the author asking about the efficiency of Option<> (which according to the answer is the same), it is not the same as my question that makes reference to an array of fixed type and size and not a dynamic data type
https://stackoverflow.com/questions/28656387/initialize-a-large-fixed-size-array-with-non-copy-types He is asking about how to initialize with None, but unfortunately it didn't help to know whether the None inside the array (which is a data type of fixed size and type) will occupy additional size in memory or not.

问题

考虑下面的代码

fn main() {
    let my_array: [Option<MyStruct>; 5] = [
        Some(MyStruct{ field1: 1, field2: 2, field3: 3 }),
        Some(MyStruct{ field1: 1, field2: 2, field3: 3 }),
        None,
        Some(MyStruct{ field1: 1, field2: 2, field3: 3 }),
        None,
    ];
}

struct MyStruct {
    field1: i32,
    field2: i32,
    field3: i32,
}

考虑到使用一个大小设置为5的类型为Option<MyStruct>的数组,它是否会占用12个字节+enum标志选项,即使数组索引位置2的元素是None

或者,当数组索引2位置的元素为Some(MyStruct)时,

如果Rust编译器在这方面的效率不够高,那么在C++中与以下内容相当的是什么:

#include <iostream>

struct Example {
    int a;
    int b;
};

int main(){
    Example* examples[5];

    /*Initialize examples at position 2*/
    examples[2] = new Example;
    
    return 0;
}

换句话说,注意C++存储了一个指针,也就是说,它不需要存储 struct Example的12个字节(三个整数

推荐答案

Box<T>是Rust中不可为空的指针.Option<T>NoneSome(T),但Option<T>(如你链接的相关答案中所述)总是为T分配足够的空间.所以在你的例子中,没有间接指针,每个元素my_array占用size_of<MyStruct>()字节的空间.

但我们可以把两个拼图拼在一起.Option<Box<T>>是指向T的潜在可空指针.Box<T>的大小正好是指针的大小,所以不管值是否存在,Option<Box<T>>在自动内存中只需要一个指针的空间.所指向的值的动态存储仅在需要时分配,就像在C++中一样.Rust甚至有一个specific optimization,以确保Option<Box<T>>工作就像引擎盖下的T*.也就是说,在这种特殊情况下,我们甚至不需要存储"is Option empty"的指针,因为我们可以使用底层指针的nullptr值来表示它.

所以您需要一个由Option<Box<T>>组成的数组,该数组的初始值都是None.然后,您可以将其中一些设置为Some(Box::new(whatever)),并在需要时获得分配.

Rust相关问答推荐

如何优化小型固定大小数组中的搜索?

什么样的 struct 可以避免使用RefCell?

如何将元素添加到向量并返回对该元素的引用?

如何创建引用构造函数拥有的变量的对象?

铁 rust 干线无法使用PowerShell获取环境变量

在Rust中有没有办法在没有UB的情况下在指针和U64之间进行转换?

定义采用更高级类型泛型的性状

为什么`AlternateScreen`在读取输入键时需要按Enter键?

try 创建随机数以常量

借来的价值生命周期 不够长,不确定为什么它仍然是借来的

返回迭代器考虑静态生命周期类型

存储返回 impl Trait 作为特征对象的函数

没有明确地说return会产生错误:match arms have incompatible types

如何使用 Rust Governor 为每 10 秒 10 个请求创建一个 RateLimiter?

我如何取消转义,在 Rust 中多次转义的字符串?

为什么不可变特征的实现可以是可变的?

为什么我不能克隆可克隆构造函数的Vec?

如何在没有 `make_contiguous()` 的情况下对 VecDeque 进行排序或反转?

为什么这里需要类型注解?

为什么一个整型变量赋值给另一个变量后仍然可以使用?