Rust如何将枚举值存储在数组中? [英] How does Rust store enum values in arrays?

查看:162
本文介绍了Rust如何将枚举值存储在数组中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是有效的Rust:

The following is valid 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 }];
}

Rust如何存储它?第一个元素是12个字节,第二个元素是8个字节(我猜想开头是一个标记字节).它仅存储对数组中元素的引用吗?

How does Rust store this? The first element is 12 bytes while the second one is 8 (plus a tag byte in the beginning I guess). Does it only store references to the elements in the array?

推荐答案

枚举的所有变体都使用相同数量的内存(如果您的Foo类型为16字节,至少在我的机器上).枚举值的大小取决于其最大的变体(在您的示例中为One).

All variants of an enum use the same amount of memory (in case of your Foo type, 16 bytes, at least on my machine). The size of the enum's values is determined by its largest variant (One, in your example).

因此,这些值可以直接存储在数组中.

Therefore, the values can be stored in the array directly.

这篇关于Rust如何将枚举值存储在数组中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆