How does Rust store enum values in arrays?

前端 未结 2 644
执念已碎
执念已碎 2021-01-19 00:04

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         


        
2条回答
  •  余生分开走
    2021-01-19 00:35

    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.

提交回复
热议问题