Casting to a C-style enum?

I'm attempting to cast a u8 into a c-style enum, as below:

#[derive(Debug)]
pub enum Severity {
    emergency = 0,
    alert = 1,
    critical = 2,
    error = 3,
    warning = 4,
    notice = 5,
    info = 6,
    debug = 7
}

fn test(val: u8) -> Severity {
    val as Severity
}

I did a bit of googling, and found this PR that was merged in 2013, suggesting all I needed was to [derive(FromPrimitive)]. However, this results in a compiler error:

src/lib.rs:1:17: 1:30 error: use of undeclared trait name `std::num::FromPrimitive` [E0405]
src/lib.rs:1 #[derive(Debug, FromPrimitive)]
                             ^~~~~~~~~~~~~
src/lib.rs:1:17: 1:30 note: in this expansion of #[derive_FromPrimitive] (defined in src/lib.rs)

I then discovered FromPrimitive had been moved to the num crate, so I added a dependency upon that:

extern crate num;

use num::FromPrimitive;

#[derive(Debug, FromPrimitive)]
pub enum Severity {
    emergency = 0,
    alert = 1,
    critical = 2,
    error = 3,
    warning = 4,
    notice = 5,
    info = 6,
    debug = 7
}

fn test(val: u8) -> Severity {
    Severity::from_u8(val).unwrap()
}

However, this still results in an error:

src/lib.rs:5:17: 5:30 error: use of undeclared trait name `std::num::FromPrimitive` [E0405]
src/lib.rs:5 #[derive(Debug, FromPrimitive)]
                             ^~~~~~~~~~~~~
src/lib.rs:5:17: 5:30 note: in this expansion of #[derive_FromPrimitive] (defined in src/lib.rs)

I'm using rustic 1.4.0 and cargo 0.6.0 (e1ed995 2015-10-22), any helpers would be much appreciated. I was thinking this would be as easy as it is in every other language, but obviously not :cry:

Try the enum_primitive crate.

2 Likes

Sweet, that worked, thanks!