Java enum-like behavior in Rust

CaseyB

I want to have an enum where each value in the enum stores a constant array of bytes that represent the RGBA values for a color. In Java I would do this:

public enum Color {
    BLACK([0x0C, 0x00, 0x05, 0xFF]),
    BLUE([0x00, 0x2D, 0xFF, 0xFF]),
    RED([0xFF, 0x3E, 0x00, 0xFF]);

    private final byte[] rgba;

    Color(byte[] rgba) {
      this.rgba = rgba;
    }

    public int[] value() {
      return rgba;
    }
}

Then I could pass around Color types and just use color.value() to get the bytes out. This is what I have in Rust:

struct Color;

impl Color {
    pub const BLACK: [u8; 4] = [0x0C, 0x00, 0x05, 0xFF];
    pub const BLUE: [u8; 4] = [0x00, 0x2D, 0xFF, 0xFF];
    pub const RED: [u8; 4] = [0xFF, 0x3E, 0x00, 0xFF];
}

But this means that anywhere I want to pass a Color the type is [u8; 4]. I could call the struct Colors and then do pub type Color = [u8; 4]. Then you could have the type as Color but then it would be Colors::BLACK which seems weird.

SirDarius

If you want to have a strong type for the byte array in the Color struct, you can use the following notation, called a tuple struct:

struct Color([u8; 4]);

impl Color {
    pub const BLACK: Color = Color([0x0C, 0x00, 0x05, 0xFF]);
    pub const BLUE: Color = Color([0x00, 0x2D, 0xFF, 0xFF]);
    pub const RED: Color = Color([0xFF, 0x3E, 0x00, 0xFF]);
}

fn main() {
    // classic way of accessing data
    println!("{:?}", Color::BLACK.0);
    
    // using destructuring
    let Color(bytes) = Color::BLUE;
    println!("{:?}", bytes);
}

Playground link

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related