首先,我将发表一些类似的问题,但不一样(尽管有类似的标题和主题),如果你在另一个帖子中找到了我的问题的答案,请在 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个字节(三个整数