Combine Enum C-like and rust

hi i'm a embedded developer, in embedded world we always encode multiple bytes and for send or receive various of data and get one byte as data type now i know rust support C-like

enum HeaderType {
    Unknown         = 0,
    Notification    = 1,
    API             = 2,
}

and in rust enum can have specific data like this

enum MyEnum {
    A(i8),
    B(f32),
    C(u8),
}

now the solution i found in rust for my work is

#[derive(Copy, Clone)]
#[repr(C)]
pub union Params {
    unknown:        usize,
    notification:   f32,
    api:            usize,
}

#[derive(Debug, Copy, Clone)]
#[repr(u8)]
pub enum HeaderType {
    Unknown         = 0,
    Notification    = 1,
    API             = 2,
}

#[derive(Debug, Clone)]
pub struct SocketHeader {
    header_type:    HeaderType,
    params:         Params,
}

in above code header_type hold type of data and params is union that hold data

i think it will be good if can have rust code like this

enum SocketHeader {
    Unknown(usize)      = 0,
    Notification(f32)   = 1,
    API(usize)          = 2,
}

now we can have enum id and data

2 Likes

If you don't need custom tags that don't start from 0 and count up, there's repr(C) on enums already:

https://doc.rust-lang.org/reference/type-layout.html#reprc-enums-with-fields

It seems a bit inflexible to me that one cannot specify these further, e. g. choosing a u8 representation for the tag if wanted. Ah, reading further, the answer is repr(C, u8): Type layout - The Rust Reference


Also I'm not sure if your motivation here is C interop. or just the need for assigning numerical values to enums. If it's the former, note that your SocketHeader isn't repr(C), if it's the latter, the point could more clear by including an example use-case that uses the numerical value of the tag and/or using tags that don't count up from 0 as that's the default for (repr(C) or repr(u8), etc) enums anyways.

2 Likes

This is RFC 2363, arbitrary_enum_discriminant, tracking isssue

4 Likes

thank for answer but i couldn't test any of that codes this RFC is already available?

my goal is that i want id for each enum type

that can match id number

You need to use Rust nightly with #[feature(arbitrary_enum_discriminant)].

See here: Rust Playground

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.