为什么枚举需要额外的内存大小? [英] Why does an enum require extra memory size?

查看:35
本文介绍了为什么枚举需要额外的内存大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的理解是enum就像C中的union,系统会分配枚举中最大的数据类型.

My understanding is that enum is like union in C and the system will allocate the largest of the data types in the enum.

enum E1 {
    DblVal1(f64),
}

enum E2 {
    DblVal1(f64),
    DblVal2(f64),
    DblVal3(f64),
    DblVal4(f64),
}

fn main() {
    println!("Size is {}", std::mem::size_of::<E1>());
    println!("Size is {}", std::mem::size_of::<E2>());
}

为什么E1按预期占用了8个字节,而E2占用了16个字节?

Why does E1 takes up 8 bytes as expected, but E2 takes up 16 bytes?

推荐答案

在 Rust 中,与 C 不同,enum标记联合.也就是说,enum 知道它持有哪个值.所以 8 个字节是不够的,因为标签没有空间.

In Rust, unlike in C, enums are tagged unions. That is, the enum knows which value it holds. So 8 bytes wouldn't be enough because there would be no room for the tag.

这篇关于为什么枚举需要额外的内存大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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