Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Rust store enum values in arrays?

Tags:

enums

memory

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 }];
}

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?

like image 849
Peter Lenkefi Avatar asked Nov 01 '16 17:11

Peter Lenkefi


2 Answers

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.

like image 72
fjh Avatar answered Nov 15 '22 12:11

fjh


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::<Foo>());
}

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.

like image 30
Matthieu M. Avatar answered Nov 15 '22 11:11

Matthieu M.