简体   繁体   English

Rust如何在数组中存储枚举值?

[英]How does Rust store enum values in arrays?

The following is valid Rust: 以下是有效的Rust:

enum Foo {
    One(i32, i32, i32),
    Two { x: i32, y: i32 },
}

fn main() {
    let x: [Foo; 2] = [Foo::One(1, 2, 3), Foo::Two { x: 1, y: 2 }];
}

How does Rust store this? Rust如何存储这个? The first element is 12 bytes while the second one is 8 (plus a tag byte in the beginning I guess). 第一个元素是12个字节,而第二个元素是8(我想在开头加上一个标记字节)。 Does it only store references to the elements in the array? 它是否只存储对数组中元素的引用?

All variants of an enum use the same amount of memory (in case of your Foo type, 16 bytes, at least on my machine). 枚举的所有变体都使用相同数量的内存(在你的Foo类型的情况下,16个字节,至少在我的机器上)。 The size of the enum's values is determined by its largest variant ( One , in your example). 枚举值的大小由其最大变量(在您的示例中为One )确定。

Therefore, the values can be stored in the array directly. 因此,值可以直接存储在数组中。

Rust being a systems programming language, you can just ask it! Rust是一种系统编程语言,你可以问它!

use std::mem;

enum Foo {
    One(i32, i32, i32),
    Two { x: i32, y: i32 },
}

fn main() {
    println!("{}", mem::size_of::<Foo>());
}

This prints 16 on the playground. 这在操场上打印16张

And note that I did not specify whether I talked about One or Two , because it does not matter. 请注意,我没有说明我是否谈论过OneTwo ,因为它无所谓。 Foo has a unique size. Foo有一个独特的尺寸。


As a rule of thumb, you might want to avoid storing a very large variant. 根据经验,您可能希望避免存储非常大的变体。 One solution, if a single variant is much bigger than the other, is to reach out to Box . 如果一个变体比另一个变体大得多,那么一个解决方案是接触Box

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM