How does Rust store enum values in arrays?

前端 未结 2 643
执念已碎
执念已碎 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:50

    Rust being a systems programming language, you can just ask it!

    use std::mem;
    
    enum Foo {
        One(i32, i32, i32),
        Two { x: i32, y: i32 },
    }
    
    fn main() {
        println!("{}", mem::size_of::());
    }
    

    This prints 16 on the playground.

    And note that I did not specify whether I talked about One or Two, because it does not matter. Foo has a unique size.


    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.

提交回复
热议问题